网络错误axios尝试从API获取数据

13 浏览
0 Comments

网络错误axios尝试从API获取数据

我太累了,修复这个问题很麻烦。它在https下工作,但在http下不工作,请帮帮我。

当我使用这个API => https://jsonplaceholder.typicode.com/posts时,它可以工作,但是当我使用自己的API时它不工作。

这是我的代码:

import axios from 'axios'
let baseURL = ''
{
  Platform.OS == 'android'
  ? baseURL = 'http://10.0.2.2:3000/api/v1/' // android
  : baseURL = 'http://localhost:3000/api/v1/' // IOS
}
axios.get(`${baseURL}products`)
.then(res => {console.log(res) })
.catch(err => console.log(err)})

它有错误

网络错误

http://packager.x5-xy3.anonymous.g-bazar.exp.direct/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:189790:25中的createError函数

在node_modules\axios\lib\adapters\xhr.js的91行中的handleTimeout函数

在node_modules\event-target-shim\dist\event-target-shim.js的818行中的EventTarget.prototype.dispatchEvent函数

在node_modules\react-native\Libraries\Network\XMLHttpRequest.js的600行中的setReadyState函数

在node_modules\react-native\Libraries\Network\XMLHttpRequest.js的395行中的didCompleteResponse函数

在node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js的189行中的emit函数

在node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js的416行中的callFunction函数

在node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js的109行中的guard$argument_0函数

在node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js的364行中的guard函数

在node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js的108行中的callFunctionReturnFlushedQueue函数

在[native code]:null中的callFunctionReturnFlushedQueue函数

0
0 Comments

问题原因:iOS SDK要求连接必须使用https协议而不是http协议。可以在Xcode项目的info.plist文件中添加对域名的例外。

解决方法:打开项目的info.plist文件,在任意编辑器中添加以下代码到文件末尾,放在最后一个节点之前。

NSAppTransportSecurity

   NSAllowsArbitraryLoads
   

你可以点击[这个链接](https://stackoverflow.com/a/31629980/7578825)获取更多信息。

是否有其他解决方法?

0