我有这个作为我的快速服务器的配置

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())引起的;但你可以看到,我把它叫做路线之前。

有线索吗?


当前回答

我在我的案例中所做的是,我声明app.use(express.json());app.use(表达。Urlencoded ({extended: false}));在我的路线之前,问题解决了。我希望这对你也有帮助!

其他回答

请求头中的Content-Type非常重要,特别是当你从curl或任何其他工具中发布数据时。

确保你使用的是application/x-www-form-urlencoded, application/json之类的,这取决于你的post数据。将此字段保留为空将使Express混淆。

当我使用bodyParser时,它被标记为已弃用。为了避免这种情况,我使用下面的代码和express代替bodyParser。

注意:路由必须声明,最后这很重要!这里的其他回答很好地描述了这个问题。

const express = require("express");
const app = express();

const routes = require('./routes/api');

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// Routes must declared finally
app.use('/', routes);

更新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。

不。你需要在app.use(app.router)之前使用app.use(express.bodyParser())。实际上,app.use(app.router)应该是你调用的最后一个东西。