2017-03-08 185 views
1

我真的很习惯使用REST和Express,我一直在关注REST API上的这个 tutorial。这里是我的app.js代码:使用POST方法时Node.js req.body为空

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的休息便于检查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

+0

显示您的console.log(req)和console.log(req.body)的结果。您可能会以错误的格式传递POST请求。确保请求正文是JSON。您可以添加传递参数方式的图像。 – rresol

+0

如何发布POST请求? – jfriend00

+0

这可能是你对api做POST请求的方式,然后是其他任何东西。 – nozari

回答

0

在邮递员的3种选择可用于内容类型选择“X-www-form-urlencoded”,它应该工作。

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

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

的“体解析器”中间件只处理JSON和urlencoded进行数据

在邮差,与原料JSON数据有效载荷来测试HTTP后操作,选择原始选项和设置以下头参数:

Content-Type: application/json 

此外,一定要包裹在双引号作为键/值的JSON有效载荷的任何字符串。

body-parser包将解析多行原始JSON有效载荷就好了。

{ 
    "foo": "bar" 
} 
0

你需要在REST易边数据部分输入正确的MIME类型:

application/json 
+0

我试过这样做,但它仍然没有帮助。 –

0

这很可能是因为您对数据库的调用没有找到您要查找的内容。当我开始学习猫鼬时,对我来说一个巨大的痛点是我错误地预期了一个空的答案被计为err,但事实并非如此。

如果您将console.log(genre)放在您的res.sendres.json陈述之上,会发生什么情况?

此外,只是想知道,为什么你用res.send其次res.json

+0

其他语句不执行。它仍然在如果和打印“出了问题”。在Genre.addGenre导致[对象对象]之前的控制台日志记录。 –

0

好的。所以我猜这可能是一个扩展问题。我使用相同的代码在Chrome中使用POSTMAN发送POST请求,现在它工作得很好。早些时候,即使邮差没有工作,但我配置铬不使用代理服务器后,它工作得很好。

谢谢大家帮助我。