【问题标题】:Node.js req.body is empty when using POST method使用 POST 方法时,Node.js req.body 为空
【发布时间】:2017-07-29 14:43:25
【问题描述】:

我对使用 REST 和 Express 非常陌生,我一直在关注 REST API 上的 tutorial 。这是我的 app.js 代码:

var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require("mongoose");

var app = express();
var port    = parseInt(process.env.PORT, 10) || 3000;

app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

Genre = require('./models/genre');

//Connect to mongoose
mongoose.connect('mongodb://localhost/bookstore');

var db = mongoose.connection;

app.listen(port);
console.log('Running on port 3000\n\n');

app.post('/api/genres', function(req, res){
        console.log(req.body);
        var genre = req.body;
        Genre.addGenre(genre, function(err, genre){
            if (err) {
                console.log(err);
                res.send({status: 'something went wrong'});
            }else{
            res.send({status: 'saved'});
            res.json(genre);}
        });
}); 

我在 Firefox 上使用 Rest Easy 来检查 POST 请求。生成的错误是“流派验证失败”,因为正文为空。用于此的模式在模型中定义为:

var mongoose = require("mongoose");

//Genre Schema
var genreSchema = new mongoose.Schema({

    name: {
        type: String,
        required: true
    },
    create_data:{
        type: Date,
        default: Date.now
    }
});

var Genre = module.exports = mongoose.model('Genre', genreSchema);

// add genre
module.exports.addGenre = function(genre, callback){
    Genre.create(genre, callback);
};

我尝试了其他几个流行的线程,但仍然无法解决问题。我尝试重新排列模块的导入顺序,并使用“application/x-www-form-urlencoded”将数据作为表单输入。任何想法?

编辑:console.log(req.body)的输出:

{}

console.log(req) 的输出位于 jsfiddle.net 上的 jbkb1yxa 处。(StackOverflow 不允许我嵌入更多链接,因为我的信誉点很低,抱歉。) REST 简单的截图: http://imgur.com/6QmQqRV

【问题讨论】:

  • 显示你的console.log(req)和console.log(req.body)的结果。您可能以错误的格式传递 POST 请求。确保请求正文是 JSON。您可以添加传递参数方式的图像。
  • POST 请求是如何发出的?
  • 这可能是您向 api 发出 POST 请求的方式,然后是其他任何方式。
  • 这能回答你的问题吗? req.body empty on posts

标签: javascript node.js express


【解决方案1】:

您需要在 REST Easy 端的数据部分输入正确的 MIME 类型:

application/json

【讨论】:

    【解决方案2】:

    这可能是因为您对数据库的调用未找到您要查找的内容。当我第一次开始学习 Mongoose 时,我的一个巨大痛点是我错误地认为空响应会被视为 err,但事实并非如此。

    如果将console.log(genre) 放在res.sendres.json 语句上方,会记录什么?

    另外,只是想知道,您为什么使用res.send 后跟res.json

    【讨论】:

    • else 语句不执行。它保留在 if 中并打印“出现问题”。 Genre.addGenre 之前的控制台日志记录会导致 [object Object]。
    【解决方案3】:

    好的。所以我想这可能是一个扩展问题。我使用相同的代码在 chrome 中使用 POSTMAN 发送 POST 请求,现在它工作得很好。早些时候,甚至邮递员都无法正常工作,但是在我将 chrome 配置为不使用代理服务器后,它就可以正常工作了。

    感谢大家帮助我。

    【讨论】:

      【解决方案4】:

      在可用于内容类型的 3 个选项的 Postman 中,选择“X-www-form-urlencoded”,它应该可以工作。

      app.use(bodyParser.urlencoded({
        extended: true
      }));
      

      https://github.com/expressjs/body-parser

      “body-parser”中间件只处理 JSON 和 urlencoded 数据

      在 Postman 中,要使用原始 JSON 数据负载测试 HTTP 发布操作,请选择 raw 选项并设置以下标头参数:

      Content-Type: application/json
      

      此外,请务必将用作 JSON 负载中的键/值的任何字符串用双引号括起来。

      body-parser 包可以很好地解析多行原始 JSON 有效负载。

      {
          "foo": "bar"
      }
      

      【讨论】:

      • 更新,因为当我问同样的问题并花了几个小时试图了解我做错了什么时,这会弹出。较新版本的 express 不直接使用 bodyparser。这样做:` app.use(express.json()); app.use(express.urlencoded({extended: true })); `
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      • 2013-02-25
      • 2017-05-21
      • 2015-11-25
      相关资源
      最近更新 更多