简体   繁体   English

如何在 no-cors 的 fetch 请求中更改 Header?

[英]How to change Header in fetch request at no-cors?

Send a request to a server and need to send the header 'Content-Type': 'application/json'向服务器发送请求并需要发送标头 'Content-Type': 'application/json'

all this is done with fetch, but because of crossdomain have to specify所有这一切都是通过 fetch 完成的,但由于跨域必须指定

mode: 'no-cors',模式:'no-cors',

And in this mode, the browser defaults to - 'Content-Type': 'text/plain'在这种模式下,浏览器默认为 - 'Content-Type': 'text/plain'

Actually, this is the problem, since 415 error is returned Here is the entire request code实际上,这就是问题所在,因为返回了 415 错误 这里是整个请求代码

realFetch(url {
        method: 'POST',
        mode: 'no-cors',
        cache: 'no-cache',
        credentials: "same-origin",
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(dataUser)
      }).

Prompt how to solve this problem?提示如何解决这个问题? How to force the browser to change headers using fetch?如何强制浏览器使用 fetch 更改标题?

You can't.你不能。

Setting no-cors tells fetch that you do not need CORS permission and so will not doing anything that needs permission.设置no-cors告诉fetch你不需要 CORS 权限,因此不会做任何需要权限的事情。

Setting the Content-Type header to a value other than one of the three allowed by the HTML enctype attribute requires permission from the server using CORS.Content-Type标头设置为 HTML enctype属性所允许的三个值之一以外的值需要使用 CORS 的服务器的许可。

Since you have told fetch not to check for permission, it ignores your instruction to do something normally forbidden.由于您已告诉fetch不要检查权限,因此它会忽略您执行通常禁止的操作的指令。


This answer has more information about CORS and cross-origin requests. 此答案包含有关 CORS 和跨域请求的更多信息。

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

相关问题 如何在 fetch() 中使用 no-cors - How use no-cors with fetch() 无法在标头中没有 no-cors 的情况下获取 POST - Unable to fetch POST without no-cors in header 使用带有 fetch API 的“no-cors”模式时,请求标头未按预期设置 - Request header not set as expected when using 'no-cors' mode with fetch API 请求的资源上不存在 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 fetch() 也不行? - Why is my no-cors fetch() not ok even if the request succeed? 如何使用“no-cors”将 JavaScript HTTP post 请求代码更改为 C#? - How can I change JavaScript HTTP post request code to C#, using 'no-cors'? 如何在模式为“ no-cors”的情况下使用获取API获取数据? - How to get data using fetch API with mode 'no-cors'? dn 为什么在 fetch 调用中使用 no-cors? - How a dn why to use no-cors in a fetch call? 如何修复将请求的模式设置为“no-cors”? - How to fixed set the request's mode to 'no-cors'? 当在react.js中将no-cors插入标头以获取json内容时出现奇怪的错误 - strange error when including no-cors into header for fetch of json content in a react.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM