首页 > 解决方案 > Connecting to localhost with React Native

问题描述

I'm trying to fetch an json from a locally hosted express API using a react native fetch get request. Our react native code is :

 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));
  }, []);

The following error is logged when we try to send the request:

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

When sending a get request from postman, the json is displayed so I am confused what is going wrong.

标签: node.jsreact-nativeexpress

解决方案


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


推荐阅读