React-native: unsupported BodyInit type when using fetch

Created on 19 Feb 2016  路  11Comments  路  Source: facebook/react-native

Hey,
When I using fetch to post a request on 0.20.0/0.19.0 version , it get 'unsupported BodyInit type' error:

following is request :

var object = {
    method: 'POST',
    body: {
        'loginId': 'helloreact',
        "password": 'd4da22ee9d210bab31d1c3ef8b3674a6'
    }
};

fetch(url, object)
.then((response) => response.text())
.then((responseData) => {})
.catch(function(err) {});
Locked

Most helpful comment

@peter0072000 please try body: JSON.stringify(obj)

All 11 comments

@peter0072000 please try body: JSON.stringify(obj)

@peter0072000 And make sure to specify the header type. Will look something like this...

var object = {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body:JSON.stringify( {
       'loginId': 'helloreact',
       'password"' 'd4da22ee9d210bab31d1c3ef8b3674a6'
    })
};

fetch(url, object)
.then((response) => response.text())
.then((responseData) => {})
.catch(function(err) {});

Related #2538

Our server doesn't support plain/text media type in body. Tried to set 'Content-Type' header to 'application/json' also not working. How can i send request body in json?

@xahon What do you mean? If your server does not support sending plain/text in the body it could mean it does not support sending POST methods which you need to send a body. If what you meant is that you cannot change the header I would just send all in one big string like so "{'text':'message'}".

@sfratini means you are sending body as plain text - "{'text':'message'}" but we need to send as object like {'text':'message'}

why do we need to convert json object to string in the post request? sorry, but it looks like sh*t and its really annoying when you have to do something like typeof options.body === 'string' ? options.body : JSON.stringify(options.body),

Isn't the problem related to the answer and not the request?

Totally agree with @oleksandrriabykh it became boring explaining backend guys that I'm limited to send them stringified body only. They were in disbelief when told them

You can all install another fetch dependency and override the global.fetch. I am doing that right now in order to add a timeout to fetch and I am not having any of these issues.

@sfratini I tried your solution with

import fetch from 'react-native-fetch-polyfill'
GLOBAL.fetch = fetch

and had no success. Is this the override you used?
To be more specific, it fixes this issue, but then throws Request is not a constructor in the polyfill

Was this page helpful?
0 / 5 - 0 ratings