最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Native - Fetch POST not working - Stack Overflow

programmeradmin4浏览0评论

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 es 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());

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 es 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());
Share Improve this question asked Jan 12, 2017 at 6:29 Andrew IvesAndrew Ives 4872 gold badges6 silver badges12 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 6

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

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' + '/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();

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

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

server node.js?

npm i cors --save

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

res.header("Access-Control-Allow-Origin: *");
发布评论

评论列表(0)

  1. 暂无评论