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

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

有线索吗?


当前回答

Express 4,有内置的正文解析器。不需要安装单独的体解析器。所以下面的内容是可行的:

export const app = express();
app.use(express.json());

其他回答

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.

这是我今天想到的。以上方法对我都没用。但稍微搜索一下帮助我解决了这个问题。我正在为微信第三方服务器编码。

当node.js应用程序需要读取流POST数据(例如来自REST客户端的请求)时,情况会稍微复杂一些。在这种情况下,请求的属性“readable”将被设置为true,并且POST数据必须以块的形式读取,以便收集所有内容。

http://www.primaryobjects.com/CMS/Article144

添加表达。Urlencoded ({extended: true})到路由可以解决这个问题。

router.post('/save',express.urlencoded({ extended: true }),  "your route");

看来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(require('connect').bodyParser());

而不是

app.use(express.bodyParser());

我仍然不知道为什么简单的express.bodyParser()不工作…