-1

I'm making a reques in Angular 12, with a valid token in the header, in postman it works, however, if I run it from the browser, I get the following error, from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

This is part of the core, it's in a service.

token: string = 'eyJ4NXQiOiJNek15Wm1aaE9ERm...';
   headers= new HttpHeaders()
    .set('Content-type', 'application/json')
    .set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS')
    .set('Authorization', 'Bearer '+ this.token);
  getUniversal4(): Observable<Catalog>{
    console.log(this.headers);
    return this.http.get<Catalog>(this.urlEndpointBS, {headers: this.headers});
    //return this.http.get(this.urlEndpoint).pipe( map( response => response));
  }
Manuel
  • 23
  • 1
  • 6

3 Answers3

2

It's pretty self explanatory: your API server needs to respond to the preflight request (OPTIONS) with a header called Access-Control-Allow-Headers that contains the Authorization header.

Andrei Tătar
  • 7,872
  • 19
  • 37
1

The reason why the code works in Postman is that Postman does not send preflight requests whereas, your browser does.

You either can add this to your backend server:

'Access-Control-Allow-Headers', '*'

Or you can use proxy here. Just bear in mind that the proxy can be used only in the development - ng serve - and does not work in the production.

0

Although it is a long read I strongly suggest to go through the CORS page on MDN, in short:

When you trigger a request from JavaScript to an origin other of the one of the page itself, the server needs to respond with the appropriate HTTP headers - i.e. Access-Control-Allow-Headers - to the preflight request made by the browser so the browser security does not block the request.

For a longer answer see this one of a duplicate question.

acran
  • 7,070
  • 1
  • 18
  • 35