I'm trying to send a cross-origin domain and adding a custom 'Authorization'-header. Please see the code below.
Error:
XMLHttpRequest cannot load {url}. Request header field Authorization is not allowed by Access-Control-Allow-Headers.
function loadJson(from, to) { $.ajax({ //this is a 'cross-origin' domain url : "http://localhost:2180/api/index.php", dataType : 'json', data : { handler : "statistic", from : from, to : to }, beforeSend : setHeader, success : function(data) { alert("success"); }, error : function(jqXHR, textStatus, errorThrown) { alert("error"); } }); } function getToken() { var cookie = Cookie.getCookie(cookieName); var auth = jQuery.parseJSON(cookie); var token = "Token " + auth.id + ":" + auth.key; } function setHeader(xhr) { xhr.setRequestHeader('Authorization', getToken()); }
I also tried:
headers : { 'Authorization' : getToken() },
in the ajax request.
Could it be that the jquery-ajax framework is blocking cross-origin Authentification? How can I fix this?
Update:
By the way: is there a safer method to store the auth.key on client-side then in a cookie? getToken() will be replaced with a more complex method, hashing the body, date,etc.
CORS is a mechanism that defines a procedure in which the browser and the web server interact to determine whether to allow a web page to access a resource from different origin. Figure 2. Cross domain ajax request. When you do a cross-origin request, the browser sends Origin header with the current domain value.
If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.
In simple words, this error occurs when we try to access a domain/resource from another domain. To fix this, if you have access to the other domain, you will have to allow Access-Control-Allow-Origin in the server. This can be added in the headers. You can enable this for all the requests/domains or a specific domain.
This is an example of making a CORS request. If you have access to the server (which I assume you do since this is a request to localhost), you will need to add CORS-specific response headers. The simplest thing to do is to add the following response headers:
Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET, POST, PUT, DELETE Access-Control-Allow-Headers: Authorization
Your server also needs to be configured to respond to HTTP OPTIONS requests. You can learn more about making CORS requests here: http://www.html5rocks.com/en/tutorials/cors/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With