使用 React Native 连接到本地主机

Avi*_*man 3 node.js express react-native

我正在尝试使用 React Native fetch get 请求从本地托管的 Express API 获取 json。我们的反应本机代码是:

 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));
  }, []);
Run Code Online (Sandbox Code Playgroud)

当我们尝试发送请求时,会记录以下错误:

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
Run Code Online (Sandbox Code Playgroud)

当邮递员发送 get 请求时,会显示 json,所以我很困惑出了什么问题。

Vin*_*hin 8

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

adb reverse tcp:5000 tcp:5000
Run Code Online (Sandbox Code Playgroud)

现在您的链接应该可以使用了http://localhost:5000/api/listings

如果第一个选项不起作用,请尝试将您的链接替换为以下链接:

http://10.0.2.2:5000/api/listings

这是由于 Android 无法将 localhost 理解为您的 PC,对于它来说,它就是 localhost,因此在第一个选择中,我们重定向 Windows / Linux 的模拟器门流量。在 MacOS 中,不会发生此错误,因为 MacOS 知道整个环境是 localhost。