Axios API无法从Express.js(Node.js)后端接收返回数据问题排查
前端Axios调用Express后端卖家登录接口,后端返回数据但前端接收不到
前端通过Axios调用Express.js(Node.js)后端的卖家登录接口时,后端控制台能查询到卖家数据并返回响应,但前端无法接收到返回的数据。
前端代码
const { data } = await axios.create({ baseURL: `http://127.0.0.1:5000/api` }).post( "/seller/login", { sellerMobile, sellerEmail, password }, headers: { 'Content-type': 'application/json' } )
后端主文件 server.js
const app = express() app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: false })) app.use(cors()) if (process.env.NODE_ENV === "development") { app.use(morgan("dev")) } app.use("/api/seller", sellerRoutes)
路由文件 sellerRoutes.js
const router = express.Router() router.post("/login", authSeller)
控制器文件 authSeller.js
const authSeller = asyncHandler(async (req, res) => { const { email, password } = req.body const seller = await Seller.findOne({ sellerEmail: email }) if (seller) { console.log("seller data", seller) // 后端控制台能打印出数据 return res.status(201).send({ _id: seller._id, sellerEmail: seller.sellerEmail, mobile: seller.mobile, }) } else { res.status(401) throw new Error('Invalid email or password') } })
已尝试的解决步骤
- 移除并重新添加
express.json - 移除并重新添加
bodyParser.json() - 移除并重新添加
bodyParser.urlencoded({extended:false})
问题排查与解决方案
修正Axios请求格式
原前端代码中,post方法的第三个参数格式错误,Axios要求该参数为配置对象,需将headers包裹在对象内:const { data } = await axios.create({ baseURL: `http://127.0.0.1:5000/api` }).post( "/seller/login", { sellerMobile, sellerEmail, password }, { headers: { 'Content-type': 'application/json' } } )匹配请求参数键名
前端传入的参数键是sellerEmail,但后端解构的是email,会导致email值为undefined,修正控制器的参数解构:const { sellerEmail: email, password } = req.body // 或直接使用原键名 const { sellerEmail, password } = req.body const seller = await Seller.findOne({ sellerEmail })完善错误响应逻辑
若asyncHandler未正确捕获错误,throw new Error会导致请求挂起,手动返回错误响应:} else { return res.status(401).json({ message: 'Invalid email or password' }) }
内容的提问来源于stack exchange,提问作者Shubham Garg
相关产品推荐
相关产品推荐

