How to set the content-type of request header when using Fetch APi

我只是一个虾纸丫 提交于 2019-12-02 21:39:38
user1526912

I found the answer after reading the following article:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Headers

Guard

Since headers can be sent in requests and received in responses, and have various limitations about what information can and should be mutable, headers objects have a guard property. This is not exposed to the Web, but it affects which mutation operations are allowed on the headers object.

Possible guard values are:

  • none: default.
  • request: guard for a headers object obtained from a request (Request.headers).
  • request-no-cors: guard for a headers object obtained from a request created with Request.mode no-cors.
  • response: guard for a Headers obtained from a response (Response.headers).
  • immutable: Mostly used for ServiceWorkers; renders a headers object read-only.

Note: You may not append or set a request guarded Headers’ Content-Length header. Similarly, inserting Set-Cookie into a response header is not allowed: ServiceWorkers are not allowed to set cookies via synthesized responses.

When the options mode property is set to no-cors the request header values are immutable.

Instead I set the mode property to cors.

RTS

You need to create a fetch headers object.

sendRequest(url, method, body) {
    const options = {
        method: method,
        headers: new Headers({'content-type': 'application/json'}),
        mode: 'no-cors'
    };

    options.body = JSON.stringify(body);

    return fetch(url, options);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!