【问题标题】:In Express.js with body-parser the value of request.body is undefined在带有 body-parser 的 Express.js 中,request.body 的值是未定义的
【发布时间】:2014-11-19 15:13:28
【问题描述】:

我遇到了无法诊断的问题。

在服务器上,我有一个使用 Express.js 的简单 URL 处理程序:

var express = require('express');
var app = express();

var bodyParser = require('body-parser');
var multer = require('multer');

app.configure(function() {
    app.use(app.router);
    app.use(bodyParser.json()); // see: http://expressjs.com/api.html#req.body
    app.use(bodyParser.urlencoded({
        extended: true
    }));
});

app.post('/submit', function (req, res) {
    console.log(req.body);
});

在客户端,有一个由 Angular 控制器处理的表单:

$scope.submit = function () {
    // $http.post('/submit', $scope.data); // POST request to send data to the server
    $http({
        method: 'POST',
        url: '/submit',
        data: $scope.data
    });

    console.log('POST /submit ' + JSON.stringify($scope.data));
};

在浏览器的控制台中一切正常:$scope.data 有效;正如预期的那样,Node.js 也以console.log 响应,但写入undefined,这意味着request.body 未定义。

我做错了什么?我该如何解决?

【问题讨论】:

  • 浏览器控制台中网络选项卡中的请求是否有正文?
  • 您使用的是什么版本的 express?文档说:All routing methods will be added in the order in which they appear. You should not do app.use(app.router). This eliminates the most common issue with Express.github.com/strongloop/express/wiki/New-features-in-4.x
  • 我使用 Express 3.2.4,我完全确定 app.router 超出了这个问题的范围。

标签: angularjs node.js express httprequest


【解决方案1】:

如果您使用的是 Express 3,则不必使用 body-parser 模块,因为它已经与 Express 3 捆绑在一起> 作为express.bodyParser。你得到一个空的身体,因为你把 app.use(app.router) 放在身体解析器之前。

app.configure(function() {
    app.use(express.bodyParser());
    app.use(app.router);
});

这就是您的其他解决方案有效的原因:

app.post('/submit', bodyParser.json(), function (req, res) {

【讨论】:

  • 我试着把它放在后面,但没有一个 URI 处理程序起作用。把它拿出来,一切都很好。但是,在许多其他类似的问题中,我看到了完全相反的建议。
【解决方案2】:

嗯,我刚刚想出了解决方案,它确实有效。 Here 使用 body-parser 的 app.post 用几句话来解释。所以我将 POST 请求处理程序定义更改为:

app.post('/submit', bodyParser.json(), function (req, res) {
    console.log(req.body);
});

现在不仅console.log(req.body) 返回有效数据,而且在服务器上正确反序列化为 JSON,无需任何额外代码(这是 Angular+Node 对所期望的)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多