NodeJS 使用React Native连接到localhost

r3i60tvu  于 2023-05-17  发布在  Node.js
关注(0)|答案(4)|浏览(130)

我正在尝试使用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,所以我很困惑哪里出了问题。

e4yzc0pl

e4yzc0pl1#

我相信下面的代码会对你有所帮助。在terminal / cmd中输入。您的模拟器必须打开。

adb reverse tcp:5000 tcp:5000

现在你的链接应该工作http://localhost:5000/api/listings
如果第一个选项不起作用,请尝试将您的链接替换为以下链接:
http://10.0.2.2:5000/api/listings
这是由于Android不理解localhost作为您的PC,因为它是localhost,所以在第一个选择中,我们重定向Windows / Linux的模拟器门流量。在MacOS中不会发生此错误,因为MacOS理解整个环境是localhost。

olqngx59

olqngx592#

运行以下命令访问localhost或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
hl0ma9xz

hl0ma9xz3#

开发环境是一个上下文,android runner环境(如果是这样的话)是另一个上下文。
如果你的后端在node中,你可以使用serve lib。它是如此独立,我认为这是最简单的形式。
如果您使用的是Linux(类似Debian),您也可以在/etc/hosts/ file中配置主机。

ijnw1ujt

ijnw1ujt4#

只需使用您的IP地址而不是localhost

http://localhost:5000/api/listings

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

相关问题