gpt4 book ai didi

javascript - 将 'no-cors' 模式与获取 API 一起使用时,请求 header 未按预期设置

转载 作者:数据小太阳 更新时间:2023-10-29 06:14:51 24 4
gpt4 key购买 nike

我有一个请求类型似乎正在改变的抓取,这弄乱了我的帖子。我提交我的基本表格(只有一个字段)。这是提取。

      handleSubmit(event, data) {
//alert('A name was submitted: ' + this.state.value);
event.preventDefault();
console.log("SUBMIT STATE::", this.state.value);
return (
fetch("//localhost:5000/api/values/dui/", {
method: "post",
mode: 'no-cors',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
name: this.state.value,
})
}).then(response => {
if (response.status >= 400) {
this.setState({
value: 'no greeting - status > 400'
});
throw new Error('no greeting - throw');
}
return response.text()
}).then(data => {
var myData = JSON.parse(data);
this.setState({
greeting: myData.name,
path: myData.link
});
}).catch(() => {
this.setState({
value: 'no greeting - cb catch'
})
})
);


}

但是当我在 fiddler 中查看时,内容类型现在是“内容类型:文本/纯文本;字符集=UTF-8”。这是原始的 fiddler :

POST http://localhost:5000/api/values/dui/ HTTP/1.1
Host: localhost:5000
Connection: keep-alive
Content-Length: 16
accept: application/json
Origin: http://evil.com/
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36

内容类型:文本/纯文本;字符集=UTF-8 推荐人:http://localhost:3000/ 接受编码:gzip、deflate、br 接受语言:en-US,en;q=0.8

{"name":"molly"}

在 DOM Inspector 中我只看到:

发布http://localhost:5000/api/values/dui/ 415(不支持的媒体类型)

我还觉得奇怪的是,“accept”和“content-type”一样都是小写的。发生这种情况的任何原因。我还没有在我的搜索中找到任何具体的内容。

最佳答案

当为请求设置no-cors 模式时,浏览器将不允许您设置除CORS-safelisted request-headers 之外的任何请求 header 。 .参见 the spec requirements about adding headers :

To append a name/value (name/value) pair to a Headers object (headers), run these steps:

  1. Otherwise, if guard is "request-no-cors" and name/value is not a CORS-safelisted request-header, return.

在该算法中,return 等同于“返回而不将该 header 添加到 Headers 对象”。

它被设置为 text/plain;charset=UTF-8 的原因是因为 the algorithm for the request constructor调用 extract a body algorithm其中包括此步骤:

Switch on object’s type:

USVString

  • Set Content-Type to text/plain;charset=UTF-8.

关于javascript - 将 'no-cors' 模式与获取 API 一起使用时,请求 header 未按预期设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42372834/

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