【发布时间】:2020-11-30 15:52:45
【问题描述】:
我正在尝试从 Expo (React-Native) 应用程序向我的 PC 上运行的 node.js 服务器执行 HTTP 请求,但是我在使其正常工作时遇到了一些麻烦。我正在使用 ngrok 公开 localhost 并在 fetch 中使用 ngrok 服务器,但我继续收到网络请求在我的 POST 请求时失败。
我正在按如下方式创建我的服务器:
app.listen(process.env.PORT, () => {
console.log(`Application is listening on ${process.env.PORT}`);
(async function () {
const endpoint = await ngrok.connect(process.env.PORT);
console.log(
`Publicly accessible tunnel to localhost:${process.env.PORT} is available on ${endpoint}`
);
})();
});
其中 process.env.PORT 设置为 3000。当我启动服务器时,它成功连接,我能够通过 Postman 发送 HTTP 请求并成功查看注入到我的 mongoDB 数据库的数据。
现在,对于我的前端提取,我有以下代码:
try {
let response = await fetch(`https://0b02aa4f40e2.ngrok.io/signup`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password,
}),
})
.then((response) => response.json())
.then((state) => this.setState(state));
console.log(response);
} catch (err) {
console.log("Fetch didnt work.");
console.log(err);
}
其中 fetch url 是 ngrok 在服务器启动时提供的 url。我只是做一些基本的帖子配置并传递一些我通过应用程序输入的电子邮件/密码。但是,fetch 总是失败,我最终会遇到如下相同的错误:
Network request failed
- node_modules\whatwg-fetch\dist\fetch.umd.js:487:17 in setTimeout$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:135:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:387:16 in callTimers
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425:19 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
我不知道我在这里做错了什么或我错过了什么。
我正在使用我的 iPhone 进行测试。我有 android 模拟器设置,但还没有尝试过,认为它会产生相同的结果。
【问题讨论】:
标签: node.js react-native localhost expo ngrok