MZH
MZH

Reputation: 1514

Request Header doesn't work for cross-domain Ajax

I'm trying to add a parameter in the request header and it works fine for same-domain calls, but if I call a different domain (the API) I need to change the header param itself.

This is the code I've tried to add a parameter.

jqXHR.setRequestHeader(
  "Authorization", 'bearer t-7614f875-8423-4f20-a674-d7cf3096290e'
);

Should be like this

Authorization: bearer t-3e57cc74-3e7a-4fc7-9bbb-f6c83252db01
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

But for cross-domain calls it becomes like this:

Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Access-Control-Request-Headers  authorization
Access-Control-Request-Method   GET

Can anyone give me any idea how to fix this for cross-domain calls?

Upvotes: 1

Views: 1555

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318468

You need to implement the "preflighting" part of CORS since you use custom headers. There is a good documentation on it on MDN.

You basically need to handle a HTTP OPTIONS request and respond with the proper headers indicating the client that the request is allowed. If you simply want to allow all GET requests with the Authorization header the following response headers would do the job:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET
Access-Control-Allow-Headers: authorization

Upvotes: 2

Related Questions