gpt4 book ai didi

javascript - 简单请求中的 Cors 错误 : Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

转载 作者:可可西里 更新时间:2023-11-01 16:32:46 24 4
gpt4 key购买 nike

我想从虚拟网页向网络应用程序(部署在同一子网中的服务器上)发送请求。问题是我不能使用 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 header 中使用 authorization 进行响应。现在,您的服务器仅将该 header 设置为 accept, content-type, x-auth-token。或者您需要从 JS 示例中删除 Authorization header 。在 JS 示例中您设置了它,但在 JQuery 中您没有设置。这就是您得到不同结果的原因。

关于javascript - 简单请求中的 Cors 错误 : Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35704559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com