node.js - 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.
解决方案
我相信下面的代码会对你有所帮助。在终端/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。
推荐阅读
- python - RequestTimeTooSkewed:在线程中运行时,boto3 上传有时会失败
- c - 如果选择超时,套接字会发生什么
- flask - 尝试使用flask和jinja2在文件夹中显示随机图像,但当前显示的是不在文件夹中的不同文件
- angular - 当jwt访问令牌使用角度过期时如何自动注销应用程序?
- javascript - P5.js 无法在 Safari 上运行,控制台中没有错误
- html - 如何在手机上边到边显示图像
- python - itemloader add_value 列表的 Scrapy 问题
- java - Avro 消息 - InvalidNumberEncodingException 反序列化逻辑类型日期
- amazon-web-services - 创建整个 S3 存储桶的副本的最佳方法是什么
- flutter - GoogleMaps Flutter 插件 MissingPluginException