React native、Nodejs、Express、MongoDB 的 Axios 网络错误

Axios Network Error with React native, Nodejs, Express, MongoDB

提问人:안태찬 提问时间:7/10/2022 更新时间:7/11/2022 访问量:814

问:

我正在尝试使用服务器开发应用程序。 我有以下设置。
React 原生 Expo-cli
nodejs + express
mongodb

我在将客户端程序和服务器程序与物理 android 手机和 ios 手机连接时遇到了一些问题。
我通过ssh记录了linux服务器程序,其IP地址和使用的端口如下:
服务器ip:102.249.18.175
端口:443

部分前端代码如下

try {
      const response = await axios.post(
        "http://192.249.18.175:443/userAuth/signin",
        {
          email,
          password,
        }
      );

      console.log("signin response: ", response);

      if (response.data.succ) {
        return Alert.alert("로그인 성공");
      } else {
        // login fail ...
        return Alert.alert("로그인 정보가 맞지 않습니다, 다시 입력해주세요");
      }
    } catch (e) {
      const errorResponse = (e as AxiosError).response;
      console.error(errorResponse);
      // if (errorResponse) {
      //   Alert.alert("알림", errorResponse.data.message);
      // }

      console.log("Hello world!");
      return Alert.alert(`Error: ${JSON.stringify(e.response)}`);
    }



这是后端代码的一部分

app.post("/userAuth/signin", async (req, res) => {
  const { email, password } = req.body;
  console.log(req.body);
  isLocated = await userAuth.find({ email: email, password: password });
  if (isLocated) {
    res.status(200).json({ succ: true });
  } else {
    res.status(404).json({ succ: false });
  }
});

这是控制台上记录的输出,即 E.Response

Hello world!

XMLHttpRequest {
  "DONE": 4,
  "HEADERS_RECEIVED": 2,
  "LOADING": 3,
  "OPENED": 1,
  "UNSENT": 0,
  "_aborted": false,
  "_cachedResponse": undefined,
  "_hasError": true,
  "_headers": Object {
    "accept": "application/json, text/plain, */*",
    "content-type": "application/json",
  },
  "_incrementalEvents": false,
  "_lowerCaseResponseHeaders": Object {},
  "_method": "POST",
  "_perfKey": "network_XMLHttpRequest_http://192.249.18.175:443/userAuth/signin",
  "_performanceLogger": PerformanceLogger {
    "_closed": false,
    "_extras": Object {},
    "_pointExtras": Object {},
    "_points": Object {
      "initializeCore_end": 1657466704543,
      "initializeCore_start": 1657466704328,
    },
    "_timespans": Object {
      "network_XMLHttpRequest_http://143.248.219.186:19000/logs": Object {
        "endExtras": undefined,
        "endTime": 1657466705712,
        "startExtras": undefined,
        "startTime": 1657466705643,
        "totalTime": 69,
      },
      "network_XMLHttpRequest_http://143.248.219.186:19000/symbolicate": Object {
        "endExtras": undefined,
        "endTime": 1657466844264,
        "startExtras": undefined,
        "startTime": 1657466844224,
        "totalTime": 40,
      },
      "network_XMLHttpRequest_http://192.249.18.175:443/userAuth/signin": Object {
        "startExtras": undefined,
        "startTime": 1657466713331,
      },
    },
  },
  "_requestId": null,
  "_response": "Failed to connect to /192.249.18.175:443",
  "_responseType": "",
  "_sent": true,
  "_subscriptions": Array [],
  "_timedOut": false,
  "_trackingName": "unknown",
  "_url": "http://192.249.18.175:443/userAuth/signin",
  "data": undefined,
  "readyState": 4,
  "responseHeaders": undefined,
  "status": 0,
  "timeout": 0,
  "upload": XMLHttpRequestEventTarget {},
  "withCredentials": true,
}
at node_modules\expo\build\environment\react-native-logs.fx.js:27:4 in error
at node_modules\@babel\runtime\helpers\regeneratorRuntime.js:86:13 in tryCatch
at node_modules\@babel\runtime\helpers\regeneratorRuntime.js:66:31 in <anonymous>
at node_modules\@babel\runtime\helpers\regeneratorRuntime.js:86:13 in tryCatch
at node_modules\@babel\runtime\helpers\regeneratorRuntime.js:124:27 in invoke
at node_modules\@babel\runtime\helpers\regeneratorRuntime.js:132:16 in PromiseImpl.resolve.then$argument_1
at node_modules\react-native\node_modules\promise\setimmediate\core.js:37:13 in tryCallOne
at node_modules\react-native\node_modules\promise\setimmediate\core.js:123:24 in setImmediate$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:248:12 in _allocateCallback$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:112:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:162:14 in _callReactNativeMicrotasksPass
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:413:41 in callReactNativeMicrotasks
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:391:6 in __callReactNativeMicrotasks
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:133:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:368:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:132:4 in flushedQueue

我成功连接了服务器和mongodb。

[nodemon] 2.0.19
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
Server started at 443
connected to mongoDB

你对这个问题有什么见解吗?
感谢您阅读本文。

React-Native Express HTTP Axios Expo

评论

0赞 Heiko Theißen 7/10/2022
你真的用吗?端口 443 通常用于 ,而不是 。http://192.249.18.175:443httpshttp
0赞 안태찬 7/11/2022
是的,我目前使用端口 443。
0赞 안태찬 7/11/2022
在端口 443 之前,我使用了端口 80,但结果相同。

答:

0赞 Cristian Riță 7/11/2022 #1

问题可能是您尝试通过 HTTP 发出请求。对于 android,尝试启用明文网络流量,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>

同样,在 iOS 上,您具有 NSAppTransportSecurity 设置。您可以像这样修改 Info.plist 文件:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

请注意,您应该只允许开发时的 HTTP 流量。请确保在生产环境中还原这些更改。