我真的很習慣使用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
顯示您的console.log(req)和console.log(req.body)的結果。您可能會以錯誤的格式傳遞POST請求。確保請求正文是JSON。您可以添加傳遞參數方式的圖像。 – rresol
如何發佈POST請求? – jfriend00
這可能是你對api做POST請求的方式,然後是其他任何東西。 – nozari