You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native(Expo)向Node.js/Express发起POST请求无响应求助

问题排查与修复方案

核心问题1:Node.js服务器未启动监听端口

你的Express代码仅定义了路由,但未启动服务器监听指定端口,导致请求根本无法送达服务器。必须在代码末尾添加监听逻辑:

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});

运行服务器后,控制台会输出启动提示,确认服务器正常运行。

核心问题2:React Native请求URL配置错误

本地开发时,模拟器/真机无法直接访问电脑的localhost,必须替换为电脑的局域网IP地址。比如服务器跑在3000端口,URL应写成:

const url = 'http://你的电脑局域网IP:3000/g_data/auth';

可通过ifconfig(Mac/Linux)或ipconfig(Windows)查看电脑局域网IP,同时要确保URL路径/g_data/auth与Express路由完全匹配。

问题3:Fetch的timeout参数无效

原生fetch不支持timeout选项,你设置的timeout:20000不会生效,超时后无法触发catch逻辑。需用AbortController实现超时控制:

const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 20000);

const options = {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json;charset=UTF-8'
  },
  body: JSON.stringify({ a: 10, b: 20 }),
  signal: controller.signal
};

fetch(url, options)
.then(response => {
  clearTimeout(timeoutId);
  console.log(response.status);
})
.catch(error => {
  if (error.name === 'AbortError') {
    console.error('请求超时');
  } else {
    console.error('请求出错:', error);
  }
});

可选:真机测试的跨域问题

若用真机测试,需确保服务器允许跨域请求,安装并使用cors中间件:

npm install cors
const cors = require('cors');
app.use(cors());

内容的提问来源于stack exchange,提问作者789087

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 21:55:27