简体   繁体   English

访问本地主机 api 时,如何修复 react-native 中的网络错误

[英]How to fix network error in react-native when access localhost api

We're trying to connect to an API (.net core 2.2) from react-native (version 0.59), via localhost, both apparently running on the same ip, different ports, react-native on port 8080, and the api on the 44344, the issue happens the moment we fetch the url from react-native我们正在尝试通过本地主机从 react-native(版本 0.59)连接到 API(.net 核心 2.2),两者显然运行在相同的 ip,不同的端口,端口 8080 上的 react-native,以及问题上的 882902841354484发生在我们从 react-native 获取 url 的那一刻

We've also tested running the url from Postman and everything seems ok, also from any of the web browser installed (safari/chrome), even we tested the browser INSIDE react-native iOS, and it works.我们还测试了从 Postman 运行 url 并且一切似乎都正常,也从安装的任何 web 浏览器(safari/chrome),甚至我们测试了浏览器 INSIDE react-native iOS,并且它有效。

Any api running outside localhost works perfectly, is the localhost were we failed.在 localhost 之外运行的任何 api 都可以完美运行,是我们失败的 localhost。

Network request failed.

onerror
    whatwg-fetch.js:504:29
dispatchEvent
    event-target.js:172:43
setReadyState
    XMLHttpRequest.js:580:29
__didCompleteResponse
    XMLHttpRequest.js:394:25
emit
    EventEmitter.js:190:12
__callFunction
    MessageQueue.js:366:47
<unknown>
    MessageQueue.js:106:26
__guard
    MessageQueue.js:314:10
callFunctionReturnFlushedQueue
    MessageQueue.js:105:17
callFunctionReturnFlushedQueue
    [native code]:0

Part of the code (function) that fetch the api, very simple (for now)获取api的部分代码(函数),非常简单(暂时)

async Submit(){
  //GET METHOD
  try {
        let response = await fetch('https://192.168.1.56:44344/api/values');
        let responseJson = await response.json();
        return Alert.alert(JSON.stringify(responseJson));
  } catch (error) {
        console.error(error);
  }
}

Ok first of all, we've tried EVERY possible solution,to connect my react native app to my .net core api rest, both running in localhost, this is the list so far, of the things that we've tried so far, and still no result.好的,首先,我们已经尝试了所有可能的解决方案,将我的 React 本机应用程序连接到我的 .net 核心 api rest,两者都在本地主机上运行,这是到目前为止我们已经尝试过的事情的列表,并且仍然没有结果。

  • Localhost本地主机
  • 127.0.0.1 127.0.0.1
  • Computer ip .network ip not mac address)计算机 ip .network ip 不是 mac 地址)
  • React Native blank project (from the ground up) React Native 空白项目(从头开始)
  • API .net core blank project (from the ground up) API .net 核心空白项目(从头开始)
  • Running snack expo + api .net core跑步零食 expo + api .net 核心
  • ip forwarding (We can't do that do to our job policies/Not the solution we're looking for) ip 转发(我们不能这样做,因为我们的工作政策/不是我们正在寻找的解决方案)
  • http/https HTTP/https
  • Different ports不同的端口
  • Android and ios permissions from react-native来自 react-native 的 Android 和 ios 权限
  • Same.network different ip (this sorta worked, but we don't know exactly why it doesn't work running both react-native and the api in the same ip (localhost)) Same.network different ip(这种方法有效,但我们不确切知道为什么它不能在同一个 ip(本地主机)中同时运行 react-native 和 api)
  • 10.0.2.2 (for android) 10.0.2.2(安卓)
  • Enable cors on api .net core (but apparently this doesn't work on native apps, only for web)在 api .net 核心上启用 cors(但显然这不适用于本机应用程序,仅适用于网络)
  • Expose the ip through ngrok/serveo (We can't do that do to our job policies/Not the solution we're looking for)通过 ngrok/serveo 公开 ip(我们不能这样做对我们的工作政策/不是我们正在寻找的解决方案)
  • Frisbee飞盘
  • Axios Axios
  • Websocket (We can't do that do to our job policies/Not the solution we're looking for) Websocket(我们不能对我们的工作政策这样做/不是我们正在寻找的解决方案)
  • XMLHttpRequest (status code error 0) XMLHttpRequest(状态码错误0)
  • Firewall/proxy (our.network is free from firewalls and proxies)防火墙/代理(我们的网络没有防火墙和代理)
  • Web browser plugins (deactivated and/or uninstalled) Web 浏览器插件(停用和/或卸载)
  • Cache/cookies缓存/cookie
  • Docker (We can't do that do to our job policies/Not the solution we're looking for) Docker(我们不能这样做,因为我们的工作政策/不是我们正在寻找的解决方案)
  • Reboot my macbook pro重新启动我的 macbook pro

we expect react native to fetch the api, so we can continue with the office 365 login authentication.我们希望 React Native 获取 api,这样我们就可以继续进行 Office 365 登录验证。

EDIT: I just discovered that fetching the machine ip (this time running windows), with my ip being 192.168.0.9 both on the api and the react native, the fetch result showed me the 10.0.2.2:80 in the header of the json response.编辑:我刚刚发现获取机器 ip(这次运行的是 Windows),我的 ip 在 api 和 React Native 上都是 192.168.0.9,获取结果显示 881853008065878 中的 10.0.2.2:80 855014098 8380188回复。 I suppose it is the "localhost" ip from react native.我想这是来自 React Native 的“localhost”ip。 How am I supposed to fetch an ip from localhost if react native is not letting me to do so?如果本机反应不允许我这样做,我应该如何从本地主机获取 ip?

EDIT: We had to go for plan B this time around, we've made it work with a docker on the api, but I need a solution for this problem.编辑:这次我们必须为 B 计划使用 go,我们已经让它与 api 上的 docker 一起工作,但我需要一个解决这个问题的方法。 I'm 99% sure the issue is react-native and nothing else.我 99% 确定问题是 react-native 而不是别的。


EDIT: After all these weeks one of my colleges managed to solve it. 编辑:这几周之后,我的一所大学设法解决了这个问题。 First of all, we couldn't make the firewall in my macbook pro work properly. 首先,我们无法使我的 macbook pro 中的防火墙正常工作。 Second, we solved that and found out our api was having issues. 其次,我们解决了这个问题,发现我们的 api 有问题。 He found out the redirection was on https, and the certifications weren't working properly, so he changed this 他发现重定向是在 https 上,并且认证工作不正常,所以他改变了这个
"applicationUrl": "http://192.168.0.114:5001;https:192.168.0.114:5001"

to

"applicationUrl": "http://192.168.0.114:5001"

I got the same issue while fetching localhost API from react-native.我在从 react-native 获取 localhost API 时遇到了同样的问题。 Here is what I did to solve this issue.这是我为解决此问题所做的工作。 In the startups class, I removed //app.UseHttpsRedirection();在启动类中,我删除了//app.UseHttpsRedirection(); from Configure method.(Not sure if it is needed)来自配置方法。(不确定是否需要)

After that in the launchsetting.js file under the properties folder, I changed from之后在properties文件夹下的launchsetting.js文件中,我从

"applicationUrl": " https://localhost:5001;http://localhost:5000 " "applicationUrl": " https://localhost:5001;http://localhost:5000 "

to "applicationUrl": " http://localhost:5000 "“applicationUrl”:“ http://localhost:5000

and in the React native part, I simply changed my localhost with my IP:在 React 原生部分,我只是用我的 IP 更改了我的本地主机:

fetch(' http://localhost:5000/values/ ') to fetch(' http://127.0.0.1:5000/values/ ') fetch(' http://localhost:5000/values/ ') 到 fetch(' http://127.0.0.1:5000/values/ ')

This completely worked for me这完全对我有用

Take command prompt and type ipconfig, so we will be getting many addresses.在命令提示符下输入 ipconfig,这样我们就会得到很多地址。 From that take IPV4 and copy it to the clipboard.从中获取 IPV4 并将其复制到剪贴板。 Then paste this address to both the back ends port address and front end port address.然后将此地址粘贴到后端端口地址和前端端口地址。 eg say IPV4 address is 192.168.1.3 then make you your back end route API similar to this http://192.168.1.3:8080/patients , where 8080 is the port number (never mind).例如说 IPV4 地址是 192.168.1.3 然后让你的后端路由 API 类似于这个http://192.168.1.3:8080/patients ,其中 8080 是端口号(没关系)。 And use the same for the front end to grab the API result.并在前端使用相同的方法来抓取API结果。

You have to do two things.你必须做两件事。

1 - Use http://192.168.1.x:8080 (your local ip ) rather than http:// localhost:8080 in your client. 1 - 在您的客户端中使用http://192.168.1.x:8080 (您的本地 ip )而不是 http:// localhost:8080 。

2 - Add following code snippets to your .net core web api project in Startup.cs. 2 - 将以下代码片段添加到 Startup.cs 中的 .net 核心 Web api 项目。

readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

services.AddCors(options =>
        {

            options.AddPolicy(name: MyAllowSpecificOrigins,
                          builder =>
                          {
                              builder.WithOrigins("http://192.168.1.x:8080")
                              .AllowAnyHeader()
                              .AllowAnyMethod();
                          });

        });

.
.
.
app.UseCors(MyAllowSpecificOrigins);

Something that worked for me was run adb reverse tcp:<YOUR PORT> tcp:<YOUR PORT> in terminal对我有用的是在终端运行adb reverse tcp:<YOUR PORT> tcp:<YOUR PORT>

I'm not sure of how it works exactely, but I guess it makes some sort of mapping from the virtual device port to your machine's.我不确定它是如何工作的,但我猜它会从虚拟设备端口到你机器的端口进行某种映射。

Example:例子:

adb reverse tcp:8080 tcp:8080

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM