首页 > 解决方案 > 我在通过 react native 解决 android 上的获取结果时遇到了 react native 的问题

问题描述

我有一个使用 fetch 函数发出请求的函数,但我无法在 android 上获得结果,但使用相同的代码我可以在网站上获得......

功能 :

async submit() {
    var data = new FormData();
    data.append('nome', this.state.nome);
    data.append('endereco', this.state.endereco);
    data.append('foto', this.state.foto.uri);
    
    const resposta = await fetch("webapiexample.com/create.php", {
        method: 'POST',
        body: data,
    }).then((e) => e.json())
    .catch(function (error) {
        console.log("miss");
        console.log(error);
      });
    console.log(resposta)
}

在网站上我得到了这个结果:

{味精:“Inserido com sucesso!”,错误:假}

在真正的android设备上我得到了这个(未定义的是相同的console.log之前):

错过

不明确的

JSON 解析错误:无法识别的令牌 '<' [本机代码]:解析中的 null

  • node_modules\react-native\node_modules\promise\setimmediate\core.js:37:13 在 tryCallOne
  • node_modules\react-native\node_modules\promise\setimmediate\core.js:123:24 在 setImmediate$argument_0
  • _callTimer 中的 node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14
  • _callImmediatesPass 中的 node_modules\react-native\Libraries\Core\Timers\JSTimers.js:181:14
  • node_modules\react-native\Libraries\Core\Timers\JSTimers.js:441:30 在 callImmediates
  • __callImmediates 中的 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:387:6
  • __guard$argument_0 中的 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135:6
  • __guard 中的 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10
  • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:134:4 在flushedQueue
  • [本机代码]:flushedQueue 中的 null
  • [本机代码]:invokeCallbackAndReturnFlushedQueue 中的 null

标签: javascriptandroidreactjsreact-nativefetch

解决方案


此行发生错误:e.json(),服务器返回的数据不是有效的 JSON。您可以通过以下方式记录数据:

const resposta = await fetch("webapiexample.com/create.php", {
  method: 'POST',
  body: data,
}).then((e) => {
  return e.text();
}).then((text) => {
  console.log('raw text:', text);
  return JSON.parse(text);
}).catch(function (error) {
  console.log("miss");
  console.log(error);
});

通常这段代码看起来不太好,请避免将 promise 语法与 async/await 混合。


推荐阅读