跨域“与jquery.ajax Authorization'头() [英] cross-origin 'Authorization'-header with jquery.ajax()
问题描述
我试图发送一个跨域域和添加自定义Authorization'头。 请参见下面的code。
I'm trying to send a cross-origin domain and adding a custom 'Authorization'-header. Please see the code below.
错误:
XMLHtt prequest无法加载{URL}。请求头字段授权不受访问控制 - 允许 - 头不允许的。
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());
}
我也试过:
headers : { 'Authorization' : getToken() },
在Ajax请求。
这可能是因为jQuery的,Ajax框架阻止跨域身份认证?我该如何解决这个问题?
Could it be that the jquery-ajax framework is blocking cross-origin Authentification? How can I fix this?
更新:
顺便说一句:有没有更安全的方法,然后储存在客户端的auth.key在cookie? 为gettoken()将一个更复杂的方法来代替,散列体,日期等。
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请求的例子。如果你有访问服务器(我假设你这样做,因为这是一个请求到本地主机),您将需要添加CORS的具体响应头。以最简单的办法是添加以下响应报头:
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
您的服务器还需要进行配置,以对HTTP OPTIONS请求作出响应。您可以了解更多有关在这里做CORS请求:<一个href="http://www.html5rocks.com/en/tutorials/cors/">http://www.html5rocks.com/en/tutorials/cors/
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/
这篇关于跨域“与jquery.ajax Authorization'头()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!