使用React Native连接到本地主机

3

我正在尝试使用React Native的fetch get请求从本地托管的Express API中获取JSON数据。

我们的React Native代码如下:

 useEffect(() => {
    fetch("http://localhost:5000/api/listings")
      .then((response) => response.json())
      .then((responseJSON) => {
        console.log(responseJSON);
        setIsLoading(false);
        setListings(responseJSON);
      })
      .catch((error) => console.log(error));
  }, []);

当我们尝试发送请求时,会记录以下错误:
Network request failed
at http://192.168.1.34:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:30140:19 in <unknown>
at http://192.168.1.34:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:31129:20 in <unknown>
at http://192.168.1.34:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:31045:8 in _callTimer
at http://192.168.1.34:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:31253:8 in Object.callTimers
at http://192.168.1.34:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:3213:30 in MessageQueue.__callFunction
at http://192.168.1.34:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:2945:16 in <unknown>
at http://192.168.1.34:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:3167:12 in MessageQueue.__guard
at http://192.168.1.34:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:2944:13 in MessageQueue.callFunctionReturnFlushedQueue

当我在Postman中发送GET请求时,JSON被显示出来,所以我不知道出了什么问题。

1
那么,请求是从另一台设备发出的吗?如果是这样的话,localhost指的是该设备的本地主机,而不是您计算机的本地主机,您需要将localhost更改为您计算机的本地IP。 - undefined
4个回答

7

我相信下面的代码会对您有所帮助。将其输入终端/cmd中。您的模拟器必须处于打开状态。

adb reverse tcp:5000 tcp:5000

现在你的链接应该有效:http://localhost:5000/api/listings

如果第一个选项无效,请尝试使用下面的链接替换:

http://10.0.2.2:5000/api/listings

这是由于Android不认识localhost作为你的PC,对于它来说,它是本地主机,所以在第一种选择中,我们将仿真器的流量重定向到Windows/Linux。在MacOS上不会出现此错误,因为MacOS理解整个环境都是localhost。


2
运行以下命令以访问本地主机、127.0.0.1或您计算机的IP。
adb -s <device_name> reverse tcp:backend_port tcp:backend_port

例子:

adb -s emulator-5554 reverse tcp:8080tcp:8080

或者

adb reverse tcp:8080 tcp:8080

0

开发环境是一个上下文,而 Android 运行环境 (如果是这样的话) 是另一个上下文。

如果你的后台是用 Node 编写的,你可以使用serve lib。它是非常独立的,我认为这是最简单的方式。

如果你使用 Linux(类似 Debian),你还可以在 /etc/hosts/ 文件中配置主机。


0

只需使用您的IP地址而不是本地主机

http://localhost:5000/api/listings

http://IP-ADDRESS:5000/api/listings

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接