【发布时间】:2024-01-02 18:02:01
【问题描述】:
我尝试使用 fetch API 和 XHR 在某个 URL 上发布一些数据,但它们都没有工作并以 401 状态响应,当我在邮递员上测试发布请求时它工作正常。
const rawl = fetch("URL GOES HERE", {
method: 'POST',
mode: 'no-cors',
credentials: "same-origin",
data: {
"name": "SOME INPUT VALUES HERE",
"input": {}
},
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "TOKEN GOES HERE"
},
});
rawl.then((data) => {
console.log(data);
})
这个带有 fetch api,这个带有 xhr
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xmlhttp.open("POST", "URL GOES HERE", true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("Accept", "application/json");
xmlhttp.setRequestHeader("Authorization", "TOKEN GOES HERE");
xmlhttp.send({
"name": "INPUT VALUE GOES HERE",
"input": {}
});
返回错误: 对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:3000' 不允许访问。响应的 HTTP 状态代码为 401。
但在邮递员上,它通常带有相同的标题和值!!!
【问题讨论】:
标签: javascript xmlhttprequest httprequest postman fetch-api