【发布时间】:2017-03-02 17:06:20
【问题描述】:
我遇到了一个奇怪的问题,希望有一个非常简单的解决方案。我正在尝试向服务器发送 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 网络选项卡请求标头的消息如下所示:
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 网络选项卡请求标题消息如下所示:
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
由于某种原因,当我添加标题时,它会删除凭据。我已经尝试发送编码的用户:像这样在标头中传递(但显然使用真实的用户名/密码):
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));
这发生在所有浏览器中。 感谢您的所有帮助!
【问题讨论】:
-
我想我的问题确实是这样的:如何更改内容类型而不显示在 Access-Control-Request-Headers 下,而只显示默认显示 Content-Type 的位置? Postman 插件能够以某种方式让它显示出来,这似乎是解决这个问题的唯一方法。
标签: javascript rest web xmlhttprequest fetch