Andrew Ives
Andrew Ives

Reputation: 477

React Native - Fetch POST not working

I am having huge troubles getting my fetch POST calls to work on iOS. My standard Fetch calls work and the Fetch POST calls work fine on android but not iOS.

The error that comes up is "Possible Unhandled Promise Rejection (id: 0): Unexpected token < in JSON at position 0"

It actually saves the post data to my server but throws that error.

I tried debugging the network request using GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest; before the API call coupled with using CORS in my chrome debug tools. From there I can see that it is making two post calls one after the other. The first one has type "OPTIONS" while the second one has type "POST". It should probably be noted that the call works in the App while using CORS and the line of code above.

I'm very confused and have exhausted all avenues.

My code im using for refrence is as follows.

return fetch(url,{
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    }).then((res) => res.json());

Upvotes: 1

Views: 20749

Answers (5)

omprakash8080
omprakash8080

Reputation: 1391

If JSON.stringify is not working, then try to use FormData.

import FormData from 'FormData';

var formData = new FormData();
formData.append('key1', 'value');
formData.append('key2', 'value');

let postData = {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'multipart/form-data'
    },
    body: formData
}

fetch(api_url, postData)
.then((response) => response.json())
.then((responseJson) => { console.log('response:', responseJson); })
.catch((error) => { console.error(error); });

Upvotes: 6

cleverdo
cleverdo

Reputation: 11

Here is an example with date that works for me!
The trick was the "=" equal and "&" sign and has to be in a string format in the body object. Find a way to create that string and pass it to the body.

====================================

fetch('/auth/newdate/', {
            method: 'POST',
            mode: 'cors',
            redirect: 'follow',
            body: "start="+start.toLocaleString()+"&end="+end.toLocaleString()+"",
            headers: new Headers({
                "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
            })
        }).then(function(response) {
            /* handle response */
            if(response.ok) {
              response.json().then(function(json) {
                let releasedate = json;
                //sucess do something with places
                console.log(releasedate);
              });
            } else {
              console.log('Network failed with response ' + response.status + ': ' + response.statusText);
            }
        }).catch(function(resp){ console.log(resp) });

Upvotes: 1

Igor Ivanov
Igor Ivanov

Reputation: 1

server node.js?

npm i cors --save

var cors = require('cors');
app.use(cors());

res.header("Access-Control-Allow-Origin: *");

Upvotes: 0

Vishal Dhaduk
Vishal Dhaduk

Reputation: 510

You use the following code for POST request in react native easily. You need to only replace the parameter name and value and your URL only.

var details = {
    'userName': '[email protected]',
    'password': 'Password!',
    'grant_type': 'password'
};

var formBody = [];
for (var property in details) {
  var encodedKey = encodeURIComponent(property);
  var encodedValue = encodeURIComponent(details[property]);
  formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");

fetch('http://identity.azurewebsites.net' + '/token', {
  method: 'POST',
  headers: {
   'Accept': 'application/json',
   'Content-Type': 'application/x-www-form-urlencoded'
 },
 body: formBody
 }).  
 .then((response) => response.json())
        .then((responseData) => {
            console.log("Response:",responseData);
         }).catch((error) => {
                Alert.alert('problem while adding data');
            })
        .done();

Upvotes: 4

Adam Patterson
Adam Patterson

Reputation: 958

I would guess the response you are receiving is in HTML. Try:

 console.warn(xhr.responseText)


Then look at the response.

Also, IOS requires HTTPS.

Edit: Possible duplicate: "SyntaxError: Unexpected token < in JSON at position 0" in React App

Upvotes: 2

Related Questions