运行 Axios with React native 时网络错误

Network error when running Axios with React native

我正在尝试 link 我的 Django 后端与我的 React Native。目前,我正在发出一个简单的 GET 请求,以获取后端所有患者的 JSON 对象(如果有帮助,现在只存储一个)。我的电话是这样的:


async function AxiosTest() {

axios

      .get('http://127.0.0.1:8000/drugs/patients/')

      .then(function (response) {

console.log('response', response);

      })

      .catch(function (error) {

console.log('error', error.request);

      });

  }

这是通过按下按钮触发的。但是我得到的回复是:


error {"DONE": 4, "HEADERS_RECEIVED": 2, "LOADING": 3, "OPENED": 1, "UNSENT": 0, "_aborted": false, 
"_cachedResponse": undefined, "_hasError": true, "_headers": {"accept": "application/json, text/plain, 
*/*"}, "_incrementalEvents": false, "_lowerCaseResponseHeaders": {}, "_method": "GET", "_perfKey": 
"network_XMLHttpRequest_http://127.0.0.1:8000/drugs/patients/", "_requestId": null, "_response": "Failed 
to connect to /127.0.0.1:8000", "_responseType": "", "_sent": true, "_subscriptions": [], "_timedOut": 
false, "_trackingName": "unknown", "_url": "http://127.0.0.1:8000/drugs/patients/", "readyState": 4, 
"responseHeaders": undefined, "status": 0, "timeout": 0, "upload": {}, "withCredentials": true}

我有服务器 运行,我可以通过浏览器和 Postman 调用它。可能是因为它们都在不同的端口上吗?任何帮助深表感谢。谢谢!

编辑:我在 运行 使用 AVD 的 Android 模拟器上进行此操作。下面是 运行 react-native info:

的结果
    OS: Windows 10 10.0.19042
    CPU: (8) x64 Intel(R) Core(TM) i7-10510U CPU @ 1.80GHz
    Memory: 2.59 GB / 15.83 GB
  Binaries:
    Node: 14.11.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.5 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 6.14.8 - C:\Program Files\nodejs\npm.CMD
    Watchman: Not Found
  SDKs:
    Android SDK:
      API Levels: 29, 30
      Build Tools: 28.0.3, 29.0.2, 30.0.3
      System Images: android-29 | Intel x86 Atom_64, android-29 | Google APIs Intel x86 Atom
      Android NDK: Not Found
    Windows SDK: Not Found
  IDEs:
    Android Studio: Version  4.1.0.0 AI-201.8743.12.41.6953283
    Visual Studio: Not Found
  Languages:
    Java: javac 15
    Python: 3.8.7
  npmPackages:
    @react-native-community/cli: Not Found
    react: ^17.0.1 => 17.0.2
    react-native: 0.63.4 => 0.63.4
    react-native-windows: Not Found
  npmGlobalPackages:
    *react-native*: Not Found

AVD 模拟实际设备,因此您无法通过本地主机连接,因为服务器和模拟器不在同一设备上,您可以尝试将 url 指向您的实际 IP 地址

运行 ipconfig 在CMD上获取如图所示的ip

并将其添加到您的代码中,例如:

axios.get('http://{Your IP}:8000/drugs/patients/')

如果您发现自己处于与我相同的困境中,那么我希望这有助于解决您的问题。感谢 revobtz 在他们的评论中建议查看 this post,这回答了如何 link 你的 AVD 到 Django 的问题。本质上,您需要使用 10.0.2.2 而不是 localhost 或其他任何东西,因为 AVD 完全在不同的端口上工作。接下来您需要转到 Django 项目的 settings.py 并将 10.0.2.2 添加到您的 ALLOWED_HOSTS.

就是这样,应该可以让您轻松发出 GET 请求。

默认 AVD 使用 10.0.2.2,Genymotion 使用 10.0.3.2