通过 Expo 向本地主机发出 HTTP 请求

HTTP requests to localhost through Expo

我正在尝试在我的 PC 上执行从 Expo (React-Native) 应用程序到 node.js 服务器 运行 的 HTTP 请求,但是我在执行此操作时遇到了一些问题。我正在使用 ngrok 公开本地主机,并在获取中使用 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);
}

其中提取 url 是 ngrok 在服务器启动时提供的 url。我只是在做一些基本的 post 配置并传递一些 email/password 我正在通过应用程序输入的内容。但是,提取总是失败,我最终得到如下相同的错误:

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 模拟器设置,但还没有尝试过,认为它会产生相同的结果。

我将 metro bundler 连接模式设置为 LAN,我不得不将其更改为隧道,现在当我向它提供 ngrok URL 并且能够发送 post 请求时它可以正常工作。