如何解决React Native+Expo+Express+MongoDB架构下的网络错误
React Native Expo + Axios 网络错误排查与解决
问题描述
我正在开发一个用于学习的卡路里追踪应用,用Expo创建React Native前端,尝试通过Axios连接后端时遇到以下网络错误:
Network Error
at node_modules\axios\lib\adapters\xhr.js:null in handleError
at node_modules\event-target-shim\dist\event-target-shim.js:null in dispatchEvent
- ... 9 more stack frames from framework internals
已验证Postman能正常访问后端接口,但前端请求失败,查过相关讨论仍未解决。
前端代码
const addMeal = async (name, foodItems) => { return await axios .post("http://localhost:5000/meals", { title: name, foodItems: foodItems, }) .then((res) => { hideModal(); setMealName(""); }) .catch((error) => { console.log(error); }); };
后端代码
import express from "express"; import { PORT, mongDBURL } from "./config.js"; import mongoose from "mongoose"; import { Meal } from "./models/mealModels.js"; import cors from "cors"; const app = express(); app.use(cors); app.use(express.json()); app.get("/", (req, res) => { res.send({ status: "Started" }); }); // PORT = 5000 app.listen(PORT, () => { console.log(`Listening on port ${PORT}`); }); app.post("/meals", async (req, res) => { try { const newMeal = { title: req.body.title, foodItems: req.body.foodItems, }; const meal = await Meal.create(newMeal); console.log("Successful"); return res.status(201).send(meal); } catch (err) { console.log(err.message); } }); mongoose .connect(mongDBURL, { useNewUrlParser: true, useUnifiedTopology: true, }) .then(() => { console.log("Connected to database"); }) .catch((error) => { console.log(error); });
解决方案
- 替换localhost为本地IP地址:React Native模拟器/真机无法识别
localhost,需要换成电脑的本地IPv4地址(比如http://192.168.x.x:5000/meals)。可通过ipconfig(Windows)或ifconfig(Mac/Linux)查看IP。 - 修复CORS中间件调用:后端代码中
app.use(cors)缺少括号,正确写法是app.use(cors()),否则CORS中间件未初始化,会拦截跨域请求。 - 确保设备与后端同网络:模拟器/真机必须和运行后端的电脑连接同一WiFi,否则无法通信。
- 检查防火墙设置:电脑防火墙可能拦截5000端口请求,可临时关闭防火墙或添加端口允许规则测试。
- 完善后端错误响应:当前后端catch块仅打印错误,未返回响应,会导致前端触发网络错误。建议修改为:
catch (err) { console.log(err.message); return res.status(500).send({ message: err.message }); }
内容的提问来源于stack exchange,提问作者Ciremal
相关产品推荐
相关产品推荐

