Ajax POST请求体返回undefined问题:后端使用bodyParser.raw()无法获取请求体数据的原因
为什么Ajax POST请求的req.body.data返回undefined?
咱们一步步拆解问题哈:
问题根源1:后端中间件和前端Content-Type不匹配
你前端设置的contentType: 'application/x-www-form-urlencoded'是表单编码格式,但后端用了bodyParser.raw()中间件——这个中间件是把请求体当成原始二进制/纯文本数据解析的,根本不会处理表单编码的键值对结构。所以此时req.body要么是Buffer对象,要么是纯字符串,自然找不到req.body.data这个属性,返回undefined。
问题根源2:前端发送的数据格式不对
你前端传的data: input.value是纯字符串(比如假设input值是"hello",请求体就是"hello"),但表单编码格式需要的是键值对结构(比如data=hello)。就算后端中间件用对了,也没法从req.body.data拿到值,因为请求里根本没带data这个键名。
解决办法
第一步:修正后端中间件
把bodyParser.raw()换成对应表单编码的解析中间件:
- 如果是Express 4.16及以上版本,直接用内置的
express.urlencoded():app.use(express.urlencoded({ extended: true })); - 低版本Express可以用
bodyParser.urlencoded():const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: true }));
第二步:修正前端Ajax的data格式
把纯字符串包装成键值对对象,这样后端才能识别到data字段:
$.ajax({ url: "/aa", dataType: 'text', type: 'post', contentType: 'application/x-www-form-urlencoded', data: { data: input.value }, // 改成键值对结构 success: function (result) { console.log("Success", input.value); }, error: function (data) { console.log(data); } });
这样调整之后,后端再打印req.body.data就能拿到你前端传入的input值啦~
内容的提问来源于stack exchange,提问作者Özgür Arslan
相关产品推荐
相关产品推荐

