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

user1526912 picture user1526912 · Jul 2, 2016 · Viewed 72.2k times · Source

I am using npm 'isomorphic-fetch' to send requests. The problem I am experiencing is I am unable to set the content-type of the request header.

I set a content type of application/json , however the request header are being set to text/plain.

import 'isomorphic-fetch';

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

    options.body = JSON.stringify(body);

    return fetch(url, options);
  }

When I examine the request in my browser the content type is o :

content-type:text/plain;charset=UTF-8

Can anyone explain why I am unable to set this property?

Answer

RTS picture RTS · Jul 15, 2016

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