首页 > 解决方案 > 使用 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 它没有

标签: javascriptnode.jsreact-nativeaxios

解决方案


本地开发服务器无法访问,因为端口尚未被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

推荐阅读