【问题标题】:Network error axios trying to get data from API网络错误 axios 试图从 API 获取数据
【发布时间】:2021-08-25 05:33:35
【问题描述】:

解决这个问题我太累了,我无法在 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:24 in handleTimeout 在 EventTarget.prototype.dispatchEvent 中的 node_modules\event-target-shim\dist\event-target-shim.js:818:20 在 setReadyState 中的 node_modules\react-native\Libraries\Network\XMLHttpRequest.js:600:10 在 node_modules\react-native\Libraries\Network\XMLHttpRequest.js:395:6 在 didCompleteResponse 在 node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189:10 在发出 在 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in callFunction 在 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in guard$argument_0 在 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 保护 在 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 在 callFunctionReturnFlushedQueue at [native code]:null in callFunctionReturnFlushedQueue

【问题讨论】:

  • 你的后台好像阻塞了请求,需要在后台设置响应的header,请查看link
  • 您需要允许 iOS 的 http 请求。否则无法访问http请求
  • @MortadhaFadhlaoui 我的链接没问题,但如果你知道另一种方式,它有错误请帮助我
  • @Coder 在哪里我允许 IOS 的 http 请求,为什么我不能使用 http ?
  • @Coder 是对的,看看这个link

标签: reactjs react-native api axios


【解决方案1】:

iOS sdk 强制连接使用 https 协议而不是 http。您可以在 Xcode 项目的 info.plist 文件中向您的域添加例外。

使用您喜欢的任何编辑器打开项目的 info.plist 文件,然后将此代码添加到文件末尾的最后一个之前

<key>NSAppTransportSecurity</key>
<dict>
   <key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

check this link

【讨论】:

  • 您还有其他方法可以解决吗?
猜你喜欢
  • 2020-08-05
  • 2023-03-30
  • 2021-09-22
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-09
  • 1970-01-01
相关资源
最近更新 更多