我正在使用chrome中的Restlet客户端工具发布帖子请求。在console.log(res)中,我可以清楚地看到有正文存在完全正确的数据,但我仍然总是收到一条错误消息,说在执行res.body时正文是未定义的。
这是代码
var express = require('express');
var parser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
app.use(parser.urlencoded({extended: true}));
app.use(parser.json());
var db = mongoose.connection;
var port = process.env.PORT || 8000;
var router = express.Router();
router.use(function(req, res, next) {
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
router.get('/',function(req,res){
res.json({msg: 'Welcome to Pre-Health API!'});
});
var User = mongoose.Schema({
first_name: String,
last_name: String
},{
collection: 'User',
timestamps: true
});
router.route('/user').post(function(res,req) {
var user = mongoose.model('user',User);
console.log(req);
var new_user = new user({
first_name: req.body.first_name,
last_name: req.body.last_name
});
user.save(function(err) {
if(err) res.send(err);
res.json({message: "User created"});
});
});
app.use('/api',router);
app.listen(port);
console.log('API Listening on port: ' + port);
答案 0 :(得分:2)
在功能req
和res
倒置的情况下,它应该是:
router.route('/user').post(function(req, res) { ...