简体   繁体   English

使用带有 fetch API 的“no-cors”模式时,请求标头未按预期设置

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

I have a fetch where the request types seems to be changing which is messing up my post.我有一个请求,其中请求类型似乎正在改变,这弄乱了我的帖子。 I submit my basic form (one field only).我提交了我的基本表格(只有一个字段)。 Here is the fetch.这是取物。

      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'
            })
        })
    );


}

But when I look at this in fiddler content-type is now 'content-type: text/plain;charset=UTF-8'.但是,当我在 fiddler 中查看此内容时,内容类型现在是“内容类型:文本/纯文本;字符集 = UTF-8”。 Here is the raw Fiddler:这是原始的 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

content-type: text/plain;charset=UTF-8 Referer: http://localhost:3000/ Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.8内容类型:text/plain;charset=UTF-8 Referer: http://localhost:3000/ Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.8

{"name":"molly"}

In DOM Inspector I just see:在 DOM Inspector 中,我只看到:

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

I also find it strange that 'accept' is lower case as well as 'content-type'.我也觉得奇怪的是“接受”和“内容类型”都是小写的。 Any reason why this is happening.发生这种情况的任何原因。 I haven't found anything specific in my searches yet.我还没有在我的搜索中找到任何具体的东西。

When no-cors mode is set for a request, browsers won't allow you to set any request headers other than CORS-safelisted request-headers .当为请求设置no-cors模式时,浏览器将不允许您设置除CORS-safelisted request-headers之外的任何请求标 See the spec requirements about adding headers :请参阅有关添加标头的规范要求

To append a name/value ( name / value ) pair to a Headers object ( headers ), run these steps:要将名称/值 ( name / value ) 对附加到Headers对象 ( headers ),请运行以下步骤:

  1. Otherwise, if guard is " request-no-cors " and name / value is not a CORS-safelisted request-header , return.否则,如果guard是“ request-no-cors ”并且name / value不是CORS-safelisted request-header ,则返回。

In that algorithm, return equates to “return without adding that header to the Headers object”.在该算法中, return等同于“返回而不将该标头添加到 Headers 对象”。

And the reason it's instead getting set to text/plain;charset=UTF-8 is because the algorithm for the request constructor calls into an extract a body algorithm which includes this step:而是将其设置为text/plain;charset=UTF-8的原因是因为请求构造函数的算法调用了包含此步骤的提取正文算法

Switch on object ’s type:打开object的类型:

USVString USVString

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

So this is what resolved this issue, I switched 'no-cors' to 'cors'.所以这就是解决这个问题的方法,我将“no-cors”改为“cors”。 Frankly I thought I had flipped flopped these before because of cross origin issues I was having between my local development workstation and the server I was deploying to but needless to say, when I set this back to mode: 'cors', it all worked again.坦率地说,我以为我之前因为跨源问题而翻转了这些,因为我在本地开发工作站和我部署到的服务器之间遇到了跨域问题,但不用说,当我将其设置回模式:'cors'时,一切又恢复了. Both local workstation and server.本地工作站和服务器。 Why that changes the actual request header, Im not sure.为什么会改变实际的请求标头,我不确定。 If anyone has answers for that I'll gladly upvote.如果有人对此有答案,我会很乐意投票。

Thanks.谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用模式:无要求时,浏览器未添加我在前端代码中设置的请求标头 - When using mode: no-cors for a request, browser isn’t adding request header I’ve set in my frontend code 请求的资源上不存在 Access-Control-Allow-Origin header。 将请求的模式设置为 no-cors 以获取禁用 CORS 的资源 - No Access-Control-Allow-Origin header is present on the requested resource. set the request's mode to no-cors to fetch the resource with CORS disabled 如何在模式为“ no-cors”的情况下使用获取API获取数据? - How to get data using fetch API with mode 'no-cors'? 如何在 no-cors 的 fetch 请求中更改 Header? - How to change Header in fetch request at no-cors? 提取API模式:先不分配分配,然后分配函数变量 - Fetch API mode: no-cors assign then function variable 使用模式为“ no-cors”的提取polyfill,响应状态= 0 - Response status = 0 using fetch polyfill with mode: 'no-cors' 如何修复将请求的模式设置为“no-cors”? - How to fixed set the request's mode to 'no-cors'? 使用 Fetch api DELETE 方法并启用 no-cors - Using Fetch api DELETE method with no-cors enabled 尝试使用 fetch 和 pass in 模式:no-cors - Trying to use fetch and pass in mode: no-cors 无法在标头中没有 no-cors 的情况下获取 POST - Unable to fetch POST without no-cors in header
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM