我有这个作为我的快速服务器的配置
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())引起的;但你可以看到,我把它叫做路线之前。
有线索吗?
更新2022
你可以用。
app.use (express.json ())
const express = require('express')
const app = express();
const PORT = process.env.PORT || 3001
// Calling the express.json() method for parsing
app.use(express.json())
app.listen(PORT, () => {
console.log(`============ API Gateway is open at ${PORT} ============= `)
})
Express. json()是Express中内置的中间件函数。此方法用于解析带有JSON有效负载的传入请求,并基于body解析器。
该方法返回只解析JSON并且只查看内容类型头与类型选项匹配的请求的中间件。
表达。json vs bodyParser.json
看来express不再附带body解析器了。我们可能要单独安装。
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
app.use(function (req, res, next) {
console.log(req.body) // populated!
更多信息和示例请参阅git页面https://github.com/expressjs/body-parser。