JavaScript fetch() 无法将 Content-Type 标头设置为“application/json”

问题描述 投票:0回答:1

当前正在尝试将

fetch
一些 JSON 转换为 API。我正在使用
requestcatcher.com
测试我的 fetch 请求。这是一个例子,它突出了我遇到的问题:

fetch("https://example.requestcatcher.com",
{
    method: "POST",
    mode: "no-cors",
    headers: new Headers({ "Accept":"application/json", "Content-Type":"application/json" }),
    body: "{}"
});

发送此请求后,我希望请求捕获器 API 能够接收标头

Content-Type: application/json
。然而,这并没有发生 - Content-Type 不断重置为
text/plain;charset=UTF-8
。无论我传入
Headers
对象还是只是
Object
,都会发生这种情况。
Content-Type
也是唯一可以通过这种方式修改的标头 -
Accept
标头不会遇到此问题。

有趣的是,如果我传入

Content-Type: application/x-www-form-urlencoded
,这种替换就不会发生:与
application/json
不同,该标头是由请求捕获器未经更改地接收的。
application/json
似乎有一个独特的问题。我在网上没有看到关于为什么会发生这种情况的成功解释 - 如果有人能够阐明这一点,我将非常感激。

javascript json http-headers fetch-api
1个回答
0
投票

出现此问题的原因是您在

"no-cors"
选项中使用了
fetch()
模式。当使用
fetch()
模式发出
no-cors
请求时,您无法将
Content-Type header
设置为
'application/json'
,因为此模式允许非常有限的标头,并且此模式的
Content-Type header
被锁定为一些安全的标头,例如
'text/plain'

尝试删除

"no-cors"
模式,因为端点的服务器应该支持 CORS。

这是您修正的代码:

fetch("https://example.requestcatcher.com",
{
    method: "POST",
    mode: "cors", // <-- Change this
    headers: {
        "Accept":"application/json", 
        "Content-Type":"application/json"
    },
    body: "{}"
});
© www.soinside.com 2019 - 2024. All rights reserved.