Cors简单请求中的错误:请求标头字段预操作响应中的Access-Control-Allow-Headers不允许授权
问题描述:
我想从虚拟网页向Web应用发送请求(部署在同一子服务器上净)。问题是我不能使用jQuery。Cors简单请求中的错误:请求标头字段预操作响应中的Access-Control-Allow-Headers不允许授权
只有JS(不工作):
var $token;
var username = "user1";
var password = "123456";
var url = "http://192.168.110.35:8080/wwdf/api/login";
var data = {"username": username, "password": password};
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200) {
$token = xhr.responseText.access_token;
} else {
console.log("Error: readyState = " + xhr.readyState + " | Status " + xhr.status);
}
};
xhr.send(JSON.stringify(data));
JQuery的(作品):
$.ajax({
method: 'POST',
url: url,
contentType: 'application/json',
username: username,
password: password,
data: JSON.stringify(data),
headers: {
'Accept': 'application/json',
'Content-Type': 'text/plain'
},
success: function (response) {
token = response.access_token;
$("#btn").prop('disabled', true);
}
});
错误:
XMLHttpRequest cannot load http://192.168.110.35:8080/wwdf/api/login. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
网络监控:
Response
Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:accept, content-type, x-auth-token
Access-Control-Allow-Methods:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600
Content-Length:0
Date:Mon, 29 Feb 2016 15:59:29 GMT
Server:Apache-Coyote/1.1
Request Headers
Request
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization, content-type
Access-Control-Request-Method:POST
Cache-Control:max-age=0
Connection:keep-alive
Host:192.168.110.35:8080
Origin:http://192.168.12.69
Referer:http://192.168.12.69/...
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36
我不知道我在做什么错,请帮忙!
答
您需要配置服务器以在Access-Control-Allow-Headers
标头中使用authorization
进行响应。目前,您的服务器只能将该标题设置为accept, content-type, x-auth-token
。或者您需要从您的JS示例中删除Authorization
标题。在JS例子中,你设置了它,但在JQuery中你不这样做。这就是为什么你会得到不同的结果。
这工作,感谢兄弟! –
@Fourat,如果这回答你的问题,请接受它。其他人似乎觉得有帮助。 – kmanzana