javascript - 使用 React-native 访问 Node 返回未处理的 Promise 拒绝警告 (id: 0)
问题描述
我有一个测试后端路线,
router.get("/test", (req, res) => {
console.log("it works!");
return res.json({ msg: "Success from backend" });
});
在我的 react-native 组件中,我有一个方法:
export const registerUser = async () => {
const res = await axios.get("http://localhost:5000/api/users/test");
console.log("response received --> ", res.data);
};
我得到错误:
[Unhandled promise rejection: TypeError: Network request failed]
但是,当我http://localhost:5000/api/users/test
通过浏览器访问时,我得到了预期的响应和行为。
不知道我在这里做错了什么。我什至尝试使用该react-native-axios
库而不是 just axios
,但我得到了相同的错误/警告。此外,我正在将功能正常的 ReactJS 应用程序翻译为 React-native,所以我很肯定我的后端逻辑/语法已配置且正确。
编辑
完整警告如下:
编辑 2
axios 调用代码:
try {
console.log("trying");
const res = await axios.get("http://localhost:5000/api/users/test", {
headers: {
"Access-Control-Allow-Origin": "*"
}
});
console.log("got it"); // never reached
} catch (err) {
console.log("oh no"); // this doesn't log either, oddly enough
console.log(err);
}
抛出警告:
[Unhandled promise rejection: TypeError: Network request failed]
* client/node_modules/react-native/Libraries/vendor/core/whatwg-fetch.js:504:29 in onerror
* client/node_modules/event-target-shim/lib/event-target.js:172:43 in dispatchEvent
* client/node_modules/react-native/Libraries/Network/XMLHttpRequest.js:580:29 in setReadyState
* client/node_modules/react-native/Libraries/Network/XMLHttpRequest.js:394:25 in __didCompleteResponse
* client/node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:190:12 in emit
* client/node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:366:47 in __callFunction
* client/node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:106:26 in <unknown>
* client/node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:314:10 in __guard
* client/node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:105:17 in callFunctionReturnFlushedQueue
使用 Postman 或直接从浏览器工作.. 通过 React-native 它没有
解决方案
本地开发服务器无法访问,因为端口尚未被ADB
. 因此,在这种情况下,您可以映射 alocal server port
或使用 alocal IP address
来执行两个任务。
ADB
通过在终端执行以下命令来获取端口:
adb reverse tcp:5000 tcp:5000
或者
您也可以使用本地 IP。摇动仪器或按住菜单按钮打开开发者菜单。单击打开Dev Settings
,然后单击下一步。然后点击Debug server host & port for device
。在这里你可以输入你机器的本地IP和端口号5000
例子
192.168.1.50:5000
推荐阅读
- vba - 我如何使用“环境”变量将_另存为 Excel 发票在另一台计算机上
- oracle - Oracle Apex PDF 查看器
- python - 将元素放入 for lob Python 3 的新数组中
- bash - 从标准输出创建别名
- c++ - Vulkan 中的动态顶点缓冲区格式设置
- php - 为什么在使用模式编辑数据时,更改所有 ID?
- android - 无法从物理设备上的 sqlite 读取数据
- android - Android Studio 3.2 AAB 错误:使用保留文件或目录名称“lib”
- azure - 使用 azure cli 和模板创建 HDInsight + Datalake 群集时出现问题
- c# - 制作一个列表了解选择了哪个项目 C#