javascript - 我在通过 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
解决方案
此行发生错误: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 混合。
推荐阅读
- reactjs - redux 形式的谷歌地图
- jquery - jQuery 验证。验证数组数组
- python - Python:基于 id 和时间范围的对象组列表
- xslt - BizTalk - 如何以编程方式调用 Visual Studio 验证映射并保存 XSLT
- scala - 为什么在 Scala 中这条语句不是 NullPointerException?null.asInstanceOf[双]
- javascript - 2个标准输入,一个只有一次,另一个很多
- matlab - 如何在 Matlab 上保存会话
- vba - 根据单词列表从多列返回精确字符串匹配的函数
- c - 带有预处理器指令的指针
- swift - 错误的接近 UUID