简单请求中的 Cors 错误:请求标头字段 预检响应中的访问控制-允许-标头不允许授权

Cors Error in simple request: Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

本文关键字:请求 访问控制 授权 允许 响应 不允许 错误 简单 字段 Cors      更新时间:2023-09-26

我想将请求从虚拟网页发送到 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

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

您需要

将服务器配置为在Access-Control-Allow-Headers标头中使用authorization进行响应。 现在,该标头仅由您的服务器设置为accept, content-type, x-auth-token。 或者,您需要从 JS 示例中删除 Authorization 标头。 在JS示例中,您设置了它,但在JQuery中您没有。 这就是为什么你会得到不同的结果。

相关文章: