首页 > 解决方案 > 我尝试将我的 Expo 应用程序连接到 localhost 后端,但它不起作用

问题描述

我的服务器在 localhost:5000 上运行,我的 iPhone 使用 Expo 使用隧道方法连接到 Metro 服务器。我试图用我的电脑的 IP 地址更改 localhost,但日志如下:

Network request failed
at node_modules\whatwg-fetch\dist\fetch.umd.js:535:17 in setTimeout$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:383:16 in callTimers
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in callFunctionReturnFlushedQueue
at [native code]:null in callFunctionReturnFlushedQueue

我的 fetch 函数的代码是:

const onSubmitHandler = () => {
              const payload = {
                  phone,
                  name,
                  surname,
                  password,
                  city,
                  dateOfBirth,
              };
              fetch("http://192.168.1.40:5000/signup", {
                  method: 'POST',
                  headers: {
                      'Content-Type': 'application/json',
                  },
                  body: JSON.stringify(payload),
              })
              [....]
                      }
                  } catch (err) {
                      console.log(err);
                  };
              })
              .catch(err => {
                  console.log(err);
              });
          };

        

我的服务器 index.js 是:

import express from 'express';

import { createRequire } from 'module';
const require = createRequire(import.meta.url);

import sequelize from './utils/database.js';

import router from './routes/routes.js';

const app = express();

app.use(express.urlencoded({ extended: true }));

app.use(express.json());

app.use((_, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
});

app.use(router);

sequelize.sync(); 

app.listen(5000);

我该如何解决这个问题?

标签: javascriptnode.jsreactjsreact-nativeexpo

解决方案


推荐阅读