【问题标题】:Connecting to localhost with React Native使用 React Native 连接到 localhost
【发布时间】:2021-04-13 22:08:45
【问题描述】:

我正在尝试使用 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));
  }, []);

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

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

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

【问题讨论】:

  • 那么请求是从其他设备发出的吗?在这种情况下,localhost 指的是该设备的本地主机;不是您计算机的 localhost,您需要将 localhost 更改为您计算机的本地 IP。
  • @cbr 成功了!非常感谢。

标签: node.js react-native express


【解决方案1】:

我相信下面的代码会对您有所帮助。在终端/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。

【讨论】:

    【解决方案2】:

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

    如果您的后端在节点中,您可以使用serve lib。它是如此独立,我认为这是最简单的形式。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-27
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      • 2019-02-14
      相关资源
      最近更新 更多