Express POST请求提交失败,req.body始终为undefined如何解决?
问题诊断与修复方案
嘿,你猜的完全没错!问题确实出在中间件的加载顺序上——你在加载解析请求体的中间件之前,就已经挂载了路由。这就导致当路由开始处理请求时,请求体还没被解析处理,所以req.body自然就是undefined了。
问题出在哪段代码?
看你的app.js,你先执行了路由挂载:
require('./config/router')(app);
然后才加载了这些负责解析请求体的关键中间件:
app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.json())
怎么修复?
你只需要把路由挂载的代码移到所有请求体解析中间件的后面,调整后的核心代码顺序应该是这样:
// 先加载日志、请求体解析、静态文件等中间件 app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.json()) app.use(express.static(path.join(__dirname, 'views'))); // 等所有解析中间件都加载完,再挂载路由! require('./config/router')(app); // 最后才是404和错误处理中间件 app.use(function(req, res, next) { next(createError(404)); }); // ... 剩下的错误处理代码
额外小提示
另外,你可能不知道:Express 4.16版本之后,已经内置了body-parser的核心功能,所以你其实可以去掉单独安装的body-parser依赖,直接用express自带的方法就能完成请求体解析,功能完全一样,还能减少不必要的依赖。
比如把这两行:
app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.json())
替换成:
app.use(express.urlencoded({ extended: true })); // 和你原来的配置保持一致 app.use(express.json());
这样就搞定了,不用再单独引入bodyParser模块啦。
内容的提问来源于stack exchange,提问作者NashPL
相关产品推荐
相关产品推荐

