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

Express JS构建REST API时req.body返回undefined问题求助

Express中req.body输出undefined的解决办法

核心原因

Express框架默认不会自动解析JSON或URL编码格式的请求体,直接访问req.body会返回undefined。同时你的路由文件还存在模型未引入的问题,需要一并修复。

修复步骤

1. 添加请求体解析中间件

在index.js中,挂载路由之前添加解析请求体的中间件,确保Express能识别并解析请求中的数据:

const express = require('express');
const mongoose = require('mongoose');
const routes = require('./Routes/routes');
const app = express();

// 添加解析JSON和URL编码请求体的中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use('/api', routes);
  • express.json():用于解析Content-Type为application/json的请求体
  • express.urlencoded({ extended: true }):用于解析Content-Type为application/x-www-form-urlencoded的请求体(比如表单提交的数据)

2. 补充路由文件中的模型引入

你的routes.js中使用了Model但未引入对应的Mongoose模型,这会导致数据保存时报错,需要补充模型引入并确保路由正常导出:

const express = require('express');
const router = express.Router();
// 替换为你实际的模型文件路径
const Model = require('../models/YourModel'); 

router.post('/post',async (req,res) => {
    console.log("inside post router");
    console.log(req.body);
    const data = new Model({
        name: req.body.name,
        age: req.body.age
    })
    try {
       const dataToSave = await data.save();
       res.status(200).json(dataToSave)
    }
    catch(error) {
       res.status(400).json({message:error.message})
    }
})

// 确保导出路由
module.exports = router;

验证

重启Express服务器后,发送POST请求时,确保请求头的Content-Type与发送的数据格式匹配(比如JSON数据对应application/json),此时req.body就能正常获取到请求中的数据了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:45:30