将'no-CORS'模式与Fetch API一起使用时,请求标头未按预期设置 [英] Request header not set as expected when using 'no-cors' mode with fetch API

查看:46
本文介绍了将'no-CORS'模式与Fetch API一起使用时,请求标头未按预期设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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'
            })
        })
    );


}
但是,当我在fiddler中看到这一点时,Content-type现在是‘Content-type:Text/Plain;Charset=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/ Accept-编码:GZIP、DEFEATE、br 接受语言:EN-US,EN;q=0.8

{"name":"molly"}

在DOM检查器中,我只看到:

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

我还觉得奇怪的是,‘Accept’和‘Content-type’都是小写的。这一切发生的任何原因。在我的搜索中,我还没有找到任何具体的东西。

推荐答案

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

若要将名称/值(名称/)对追加到Headers对象(标头),请运行以下步骤:

  1. 否则,如果防护request-no-cors&qot;并且名称/值不是CORS-safelisted request-header,则返回。

在该算法中,return等同于"返回而不将该标头添加到Headers对象"。

将其设置为text/plain;charset=UTF-8的原因是the algorithm for the request constructor调用了包含以下步骤的extract a body algorithm

打开对象的类型:

USV字符串

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

这篇关于将'no-CORS'模式与Fetch API一起使用时,请求标头未按预期设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆