Token authentication in Angular 4

I need to retrieve data from a URL after posting the username and password. However, I encounter an error when trying to get the token using the GET method. The error message is: : Response for preflight has invalid HTTP status code 405.

@Component({
  selector: 'app-inv',
  templateUrl: './inv.component.html',
  styleUrls: ['./inv.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class InvComponent implements OnInit {
  userName= 'tcmuser';
  password= '1234pass';
  token : string;
  error: any;
  invList: any;

  constructor(private invService: InvService) { }

  ngOnInit() {
    this.invService.login(this.userName, this.password);
    this.invList = this.invService.getInvList(this.token)
    .subscribe(
      invList => this.invList = invList,
      error => this.error = error
    );
  }

}

@Injectable()
export class InvService {
  public token: string;

  constructor(private http: Http) {
    this.token = localStorage.getItem('token');
    this.http = http;

  }
  login(userName: string, password: string): Observable<any> {
    let url = `http://tcmtestapi.azurewebsites.net/api/demo/token`;
    let body = JSON.stringify({userName,password});
    let headers = new Headers({ 'Content-Type': 'application/json; charset=UTF-8' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(url, body, options)
      .map((res: any) => {
        let data = res.json();
        this.token = data.token;
        return this.token; 
      });

  }

  getInvList(token) {
    this.token = token;
    let url = `http://tcmtestapi.azurewebsites.net/api/demo/inventory`;
    let headers = new Headers({'Authorization': 'Bearer ' + this.token});
    let options = new RequestOptions({ headers: headers });
    return this.http.get(url,options)
      .map((response: Response) => response.json())
  }
}

Answer №1

Is your API configured to allow CORS requests? If it is enabled, make sure to include withCredentials: true in your code like this:

this.options = new RequestOptions({ headers: this.headers, withCredentials: true });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a TypeScript function that automatically infers the type of the returned function using generics

Suppose I want to execute the generateFunction() method which will yield the following function: // The returned function const suppliedFunction = <T>(args: T) => { return true; }; // The returned function // This is how it can be used suppli ...

Encountering 'npm install' error while trying to follow the Angular2 5 minute

I encountered an error while attempting to follow the Angular2 5 min quick start guide. Can someone assist me in resolving it? vagrant@vagrant-ubuntu-trusty-64:/vagrant/angular2-tutorial$ sudo npm install <a href="/cdn-cgi/l/email-protection" class=" ...

Tips for retrieving JSON files within karma tests

I am currently working on developing a test for my TypeScript class that involves retrieving data from a JSON file. readData<T>(filePath: string): Promise<T> { return Qajax.getJSON(filePath); } For testing purposes, I am utilizing the Jas ...

Exploring different ways to customize the grid style in Angular 6

Here is the style I am working with: .main-panel{ height: 100%; display: grid; grid-template-rows: 4rem auto; grid-template-columns: 14rem auto; grid-template-areas: 'header header''sidebar body'; } I want to know how to cha ...

I possess a pair of items that require merging together while combining any overlapping key values in their properties

I have a scenario where I need to merge two objects and concatenate strings if they have the same key. obj1 = { name: 'John', address: 'Cairo' } obj2 = { num : '1', address: 'Egypt' } After merging, the r ...

Variations in comparing tuple types in TypeScript

Exploring the TypeScript Challenge, there is a particular problem known as IsNever. The task at hand is to create a type called IsNever that takes input of type T. If the resolved type equates to never, the output should be true; otherwise, it should be fa ...

Angular5: At what point does Angular finish loading a page?

Within my angular5 application, I have implemented a table that retrieves data from the backend. After the initial load of the table, I aim to adjust the scroll position inside it. To achieve this, I am utilizing the following code: ngAfterViewInit() { ...

What is the best way to convert Observable<Observable<{...}>[ ]> to Observable<{...}[ ]>?

I am currently working on merging two observable objects into a single observable to access data from both. These observables represent documents from separate collections in a NoSQL database, specifically a Cloud Firestore database. Both collections have ...

Tips for creating an interface in TypeScript that prevents access to uninitialized properties of a class

Interfaces still baffle me a bit. I understand that interfaces are typically used for public properties, but I want to create an interface that will prevent access to uninitialized properties. Currently, I am able to access this.material without any errors ...

What is the procedure for cancelling a file upload in the FileUpload component of PrimeNG?

1. Issue Overview Looking to terminate file upload in PrimeNG's FileUpload component when certain filename patterns are detected. Using Angular 6.0.7 and PrimeNG 6.0.2. 2. Initial Strategy 2.1. HTML Code <p-fileUpload #fileUploader name="file" ...

Vue's v-on:click feature stops functioning correctly post-build

I have successfully integrated the Vue slide example from this link into my Angular template. Everything works fine when running ng serve, but after building with ng build and then trying to start it again with ng serve or from the dist folder using npm s ...

What is the function return type in a NextJS function?

In my project using NextJS 13, I've come across a layout.tsx file and found the following code snippet: export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html> <head /> <body&g ...

Can browser-sync be used to update sass/css for angular 2 components through injection?

Currently, I am using browser-sync to dynamically inject and modify the CSS in my application's root stylesheets that are not directly managed by Angular. Surprisingly, this process does not require a reload. However, I have noticed that any changes ...

Is there a way to package extra files along with `NodejsFunction` in Node.js?

I am looking to add another HTML file to the source code, like shown below. https://i.sstatic.net/OyxDM.png Here is my current code: const mailerFunction = new aws_lambda_nodejs.NodejsFunction(this, 'ApiNotificationHandler', { runtime: lambd ...

Define the interface for a GraphQL resolver argument in code-first implementation

This specific GraphQL schema example from the Constructing Types page showcases how to define the Query type. // Creating the Query type var queryType = new graphql.GraphQLObjectType({ name: 'Query', fields: { user: { type: userType ...

Methods in Ionic to call an external JavaScript file from TypeScript

Having a JSON list stored in a JavaScript file, my objective is to filter it using TypeScript before sending the filtered results to the HTML homepage. However, I encountered an issue within the HTML file. It's worth mentioning that when running the ...

Having difficulty testing an Angular/NGXS action that triggers after an unsuccessful API request

Struggling with writing tests for an NGXS action that calls an http request? Want to add tests for both successful and failed requests? Here is the code for my Action: @Action(SearchChuckNorrisJokes) searchChuckNorrisJokes({ getState, setState }: StateCo ...

Is there a way to increase the level of detail in the error trace provided by tsc? This error trace is

While attempting to compile a React project using the default tsconfig.json provided by create-react-app, I encountered a baffling error that has me stumped. $ tsc error TS2488: Type 'never' must have a '[Symbol.iterator]()' method that ...

Hold off until the operation finishes executing and then deliver Angular 6

Is there a way to delay the subscribe function until my logic is complete and the transform method has updated the keys object? transform(value: any, args:string) : any { let keys = []; this.http.get('src/app/enum-data/enum.json').subsc ...

Can a TypeScript file be created by combining a declaration file and a .js file?

It is commonly understood that declaration files are typically used for libraries rather than projects. However, let's consider a scenario where an existing JavaScript project needs to be migrated to TypeScript by creating d.ts files for each source ...