React Native - 获取 POST 不工作

React Native - Fetch POST not working

让我的 fetch POST 调用在 iOS 上工作时遇到了很大的麻烦。我的标准 Fetch 调用工作正常,Fetch POST 调用在 android 上工作正常,但在 iOS.

上工作正常

出现的错误是"Possible Unhandled Promise Rejection (id: 0): Unexpected token < in JSON at position 0"

它实际上将 post 数据保存到我的服务器但抛出该错误。

我尝试在 API 调用之前使用 GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest; 调试网络请求,并在我的 chrome 调试工具中使用 CORS。从那里我可以看到它正在一个接一个地进行两次 post 调用。第一个的类型为 "OPTIONS",而第二个的类型为 "POST"。可能应该注意的是,在使用 CORS 和上面的代码行时,该调用在应用程序中有效。

我很迷茫,想尽了所有办法。

我参考的代码如下

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

我猜您收到的回复在 HTML 中。尝试:

 console.warn(xhr.responseText)


然后看回复

此外,IOS 需要 HTTPS。

编辑:可能重复:

您可以使用下面的代码 POST 在 React Native 中轻松请求。你只需要 仅替换参数名称和值以及您的 URL。

var details = {
    'userName': 'test@gmail.com',
    '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();

服务器node.js?

npm i cors --save

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

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

如果JSON.stringify不起作用,请尝试使用 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); });

这是一个适合我的日期示例!
诀窍是“=”等号和“&”符号,并且必须在正文对象中采用字符串格式。 想办法创建该字符串并将其传递给正文。

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

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