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

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

有线索吗?


当前回答

You have to check following things for that:-
1. app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())
Implement body parser in your app.

2. Check headers in postman its should be based on your rest api's, like if your Content-Type: application/json it should be defined in your postman headers.

其他回答

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

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

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

试试这个

npm i multer --save
const express = require('express');
const multer  = require('multer');
const upload = multer();
const app = express();

app.post('/test', upload.any(), (req, res) => {
  console.log('data', req.body);
  res.setHeader('Content-Type', 'application/json');
  res.send(req.body);
});

最新版本的Express (4.x)将中间件从核心框架中分离出来。如果需要正文解析器,则需要单独安装它

npm install body-parser --save

然后在代码中这样做

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())

当我使用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);