我有这个作为我的快速服务器的配置
app.use(app.router);
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
//Handles post requests
app.use(express.bodyParser());
//Handles put requests
app.use(express.methodOverride());
但是当我在我的路由中请求req.body.something时,我得到了一些错误,指出body是未定义的。下面是一个使用req的路由示例。身体:
app.post('/admin', function(req, res){
console.log(req.body.name);
});
我读到这个问题是由缺乏app.use(express.bodyParser())引起的;但你可以看到,我把它叫做路线之前。
有线索吗?
根据@kevin-xue所说,需要声明内容类型。在我的实例中,这只发生在IE9中,因为XDomainRequest不设置内容类型,所以bodyparser和expressjs忽略了请求的主体。
我通过在将请求传递给主体解析器之前显式地设置content-type来解决这个问题,如下所示:
app.use(function(req, res, next) {
// IE9 doesn't set headers for cross-domain ajax requests
if(typeof(req.headers['content-type']) === 'undefined'){
req.headers['content-type'] = "application/json; charset=UTF-8";
}
next();
})
.use(bodyParser.json());
在express 4及以上版本中,你不需要body解析器,它们有自己的json解析方法,
在您的express应用程序的高设置级别添加
var express = require('express');
var app = express()
app.use(express.json()); //declare this to receive json objects.
其他答案没有提到,当通过fetch或其他客户端进行表达请求时。请求必须以某种方式格式化。
const response = await fetch(`${expressAddress}/controller/route`, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json' //this must be set to a json type
},
body: JSON.stringify(row) //regular js object need to be converted to json
})
如果你像这样进行取回请求。Body将按预期输出json对象。