我已经尝试了其他一些 stackoverflow 帖子中的所有解决方案,但没有解决我的问题。
这是我的app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var index = require('./routes/index');
var v1 = require('./routes/route');
app.use('/', index);
//routes for api
app.use('/v1',v1);
这是我的post
Controller
module.exports = {
createUser:function (req,res) {
console.log(req.body);
res.send('ok'+req.body.test);
}
}
req.body
返回 {}
,即使请求正文包含参数也是如此。
我正在使用 postman 插件检查 api。
更新
postman 请求
最佳答案
bodyParser 对象公开各种工厂来创建中间件。所有中间件都将使用已解析的正文填充 req.body
属性,如果没有要解析的正文(或返回错误),则填充一个空对象 {}
。
app.use(bodyParser.urlencoded({ extended: true })); // for encoded bodies
A new body object containing the parsed data is populated on the request object after the middleware,
req.body
will contain the parsed data, this object will contain key-value pairs, where the value can be a string or array
内容类型是application/x-www-form-urlencoded
app.use(bodyParser.json()); // for json encoded bodies
A new body object containing the parsed data is populated on the request object after the middleware (i.e.
req.body
).
内容类型是application/json
application/json
在您像这样发布数据 {"test":"hello"}
时使用。 www-form-url-encoded
用于在使用 app.use(bodyParser.urlencoded({ extended: true })) 时从 url 获取对象中的数据作为键值;
。它们都是不同的并且有自己的用例
关于javascript - Express js req.body 返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43227729/