2

I have the below code in my ajax request.

  beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', 'bearer t-7614f875-8423-4f20-a674-d7cf3096290e') }
  1. Initially, i need to know the purpose of xhr.setRequestHeader().
  2. while set like above , i receive the console error as

    Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

I searched a lot and so many solutions found, but i didn't understand.

Any one please explain, why we are using this and why this issue occurs and how to resolve this.

Need the easy understanding about this issue, please suggest

Karthik Ravichandran
  • 995
  • 1
  • 11
  • 21

1 Answers1

0

I imagine .setRequestHeaders() is from an old version of JQuery. It's not in the current docs. This would be a similar function:

https://api.jquery.com/jQuery.ajaxSetup/

For your error,

https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS#Preflighted_requests_in_CORS

In CORS, a preflight request with the OPTIONS method is sent, so that the server can respond whether it is acceptable to send the request with these parameters. The Access-Control-Request-Method header notifies the server as part of a preflight request that when the actual request is sent, it will be sent with a POST request method. The Access-Control-Request-Headers header notifies the server that when the actual request is sent, it will be sent with a X-PINGOTHER and Content-Type custom headers. The server now has an opportunity to determine whether it wishes to accept a request under these circumstances.

Basically it is a browser security feature to ask the server if it is OK to send your headers. If Authorization is not part of the list of acceptable headers, then the browser will give an error. It is a bug on the server side. I ran into this problem because I used Authentication header instead.

You have to use your own server to access the URL and bypass the browser security restrictions.

Chloe
  • 21,167
  • 37
  • 143
  • 289