简单请求中的Cors错误:请求标头字段预检响应中的Access-Control-Allow-Headers不允许授权

时间:2016-02-29 16:28:28

标签: javascript http cors

我想从虚拟网页向Web应用程序发送请求(部署在同一子网中的服务器上)。问题是我无法使用jQuery。

只有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

我不知道自己做错了什么,请帮忙!

1 个答案:

答案 0 :(得分:2)

您需要将服务器配置为使用authorization标头中的Access-Control-Allow-Headers进行回复。现在,您的服务器仅将该标头设置为accept, content-type, x-auth-token。或者您需要从JS示例中删除Authorization标头。在JS示例中,您可以设置它,但在JQuery中,您不需要。这就是你得到不同结果的原因。