首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeError:尝试从android模拟器访问本地API时网络请求失败。React-Native

TypeError:尝试从android模拟器访问本地API时网络请求失败。React-Native
EN

Stack Overflow用户
提问于 2021-05-07 05:59:02
回答 1查看 40关注 0票数 0

我在各处都看到了这个问题的答案,但似乎没有一个对我有效。

我正试图从我的android模拟器中执行一次react本地抓取,并命中在https://localhost:5002/v1/users上运行的本地API。

这是我的fetch现在的样子:

代码语言:javascript
复制
var response: Response = await fetch(`https://10.0.2.2:5002/v1/user/${initialContext.userId}`, {
        method: "GET", 
        headers: {
          "Authorization": `Bearer ${initialContext.accessToken}`
        }
      });

这就是我得到的错误:

代码语言:javascript
复制
Possible Unhandled Promise Rejection (id: 0):
TypeError: Network request failed
TypeError: Network request failed
    at C:\Users\raffaele.leo\Downloads\Source-Code\cbt-systems\1.x\trunk\src\CBTravel.Mobile.AirPortal\.vscode\.react\index.bundle:26139:20
    at C:\Users\raffaele.leo\Downloads\Source-Code\cbt-systems\1.x\trunk\src\CBTravel.Mobile.AirPortal\.vscode\.react\index.bundle:30727:21
    at _callTimer (C:\Users\raffaele.leo\Downloads\Source-Code\cbt-systems\1.x\trunk\src\CBTravel.Mobile.AirPortal\.vscode\.react\index.bundle:30643:9)
    at Object.callTimers (C:\Users\raffaele.leo\Downloads\Source-Code\cbt-systems\1.x\trunk\src\CBTravel.Mobile.AirPortal\.vscode\.react\index.bundle:30851:9)
    at MessageQueue.__callFunction (C:\Users\raffaele.leo\Downloads\Source-Code\cbt-systems\1.x\trunk\src\CBTravel.Mobile.AirPortal\.vscode\.react\index.bundle:2781:31)
    at C:\Users\raffaele.leo\Downloads\Source-Code\cbt-systems\1.x\trunk\src\CBTravel.Mobile.AirPortal\.vscode\.react\index.bundle:2513:17
    at MessageQueue.__guard (C:\Users\raffaele.leo\Downloads\Source-Code\cbt-systems\1.x\trunk\src\CBTravel.Mobile.AirPortal\.vscode\.react\index.bundle:2735:13)
    at MessageQueue.callFunctionReturnFlushedQueue (C:\Users\raffaele.leo\Downloads\Source-Code\cbt-systems\1.x\trunk\src\CBTravel.Mobile.AirPortal\.vscode\.react\index.bundle:2512:14)
    at C:\Users\raffaele.leo\Downloads\Source-Code\cbt-systems\1.x\trunk\src\CBTravel.Mobile.AirPortal\.vscode\.react\debuggerWorker.js:199:58
    at process.<anonymous> (C:\Users\raffaele.leo\Downloads\Source-Code\cbt-systems\1.x\trunk\src\CBTravel.Mobile.AirPortal\.vscode\.react\debuggerWorker.js:68:9)

正如您所看到的,我已经尝试使用10.0.2.2 (相当于模拟器的本地主机)运行它,并且我还尝试了我的计算机的IP地址。我还尝试过运行adb reverse和其他端口转发方法。

对我来说最难理解的部分是,如果我在我的模拟器上访问chrome上的https://10.0.2.2:5002,我就能够访问我的本地API。我还可以从那个fetch语句中命中云中的API,但不是运行在本地主机上的任何东西。

任何想法都将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2021-11-10 22:28:54

实际上,使用ngrok很容易工作,它在您的模拟器和本地主机之间工作(网络隧道)。它为您提供一个域,并将您的所有请求转发到localhost。您可以查看此文档https://ngrok.com/docs

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67426454

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档