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

Request header not set as expected when using 'no-cors' mode with fetch API

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

      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 中查看时 content-type 现在是 'content-type: text/plain;charset=UTF-8'。这是原始的提琴手:

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

content-type: text/plain;字符集=UTF-8 推荐人:http://localhost:3000/ Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.8

{"name":"molly"}

在DOMInspector中我刚看到:

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

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

这就是解决此问题的方法,我将 'no-cors' 切换为 'cors'。坦率地说,我认为我之前已经失败了,因为我在本地开发工作站和我正在部署的服务器之间遇到了跨源问题,但不用说,当我将其设置回模式时:'cors',这一切又工作了本地工作站和服务器。为什么这会更改实际请求 header,我不确定。如果有人对此有答案,我会很乐意投票。

谢谢。

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

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 等同于“return 而不是将 header 添加到 Headers object”。

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

Switch on object’s type:

USVString

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