我遇到了一个奇怪的问题,我希望有一个非常简单的解决方案。我正在尝试向服务器发送 POST 请求。我已经尝试使用 fetch 和 XMLHttpRequest 进行此操作,但没有成功。我的 xhr 请求如下所示:
var xhr = new XMLHttpRequest();
xhr.open("POST", location);
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(obj));
我的获取请求如下所示:
fetch(location, {
credentials: 'include',
method: 'post',
body: JSON.stringify({obj}),
headers: {
'Content-Type': 'application/json'
})
.then((response) => {
if (response.ok){
response = response.json();
} else {
response = {};
}
window.console.debug(response);
})
.then((json) =>{
window.console.debug(json);
})
.catch((error) => {
window.console.debug(error);
});
两者的结果相同。如果我像上面那样保留它,则不会发送凭据,因此它会发送 OPTIONS 请求,并且我收到 401。我的 Chrome 网络选项卡的消息请求 header 如下所示:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:192.168.146.101:8005
Origin:http://localhost:8555
Referer:http://localhost:8555/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
如果我删除标题行,则内容类型是错误的类型(显然),因此我收到 415。chrome 网络选项卡请求 header 消息如下所示:
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Authorization:Basic YWRtaW46YWRtaW4=
Connection:keep-alive
Content-Length:504
Content-Type:text/plain;charset=UTF-8
Host:192.168.146.101:8005
Origin:http://localhost:8555
Referer:http://localhost:8555/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
出于某种原因,当我添加 header 时,它会删除凭据。我尝试过像这样在 header 中发送编码的 user:pass (但显然使用真实的用户名/密码):
var xhr = new XMLHttpRequest();
xhr.open("POST", location);
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Basic ' + window.btoa('user:pass');
xhr.send(JSON.stringify(obj));
所有浏览器都会发生这种情况。 感谢您的帮助!
最佳答案
withCredentials 属性仅指示是否应使用凭据发出跨站点访问控制请求,我不确定这是否是您正在寻找的 https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
你尝试过这个吗?
var xhr = new XMLHttpRequest();
xhr.open("POST", location);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(user+':'+pass);
xhr.send(JSON.stringify(obj));
关于javascript - XHR POST 无法发送凭据和 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40158818/