为什么我的Express路由处理程序没有req.body值?

时间:2015-09-10 04:09:59

标签: node.js mongodb rest express

我发出这样的POST请求:

$ curl -H Content-Type: application/json -X POST -d "{'username':'xyz','password':'xyz'}" http://172.17.0.12:3000/user/add

这由我的node.js代码处理:

[root@02ffc47edbb8 mynodeapp]# cat routes/user.js
var express = require('express');
var mongoose = require('mongoose');
var bp = require('body-parser');

var router = express.Router();
var jsonParser = bp.json();
var urlencodedParser = bp.urlencoded({ extended: false });
//Mongo stuff

mongoose.connect('mongodb://172.17.0.13/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
  console.log( 'connected to the mongodb://172.17.0.13/test');
});


var userSchema = mongoose.Schema({
    username: String,
    password: String,
});

var user = mongoose.model( 'User', userSchema );

/*
 * curl -H Content-Type: application/json -X POST -
 * d '{username:xyz,password:xyz}' http://172.17.0.11:3000/user/add
 */


/* add user */
// router.post('/add', function (req, res) {
router.post('/add', jsonParser, function (req, res) {

  // console.log(req);
  console.log(req.body.username);
  if ( !req.body) return res.sendStatus(400);
  var newUser = new user({ username: 'fluffy', password: 'a' });
  newUser.save();
  res.send('respond with a resource see http://expressjs.com/api.html#app.post.method');
});

module.exports = router;

但我服务器上的输出显示req.body.usernameundefined

[root@02ffc47edbb8 mynodeapp]# DEBUG=simplist-app:* npm start

> mynodeapp@0.0.0 start /mynodeapp
> node ./bin/www

connected to the mongodb://172.17.0.13/test
undefined
POST /user/add 200 12.466 ms - 73

有人可以告诉我我做错了吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

谢谢Blakes ......我需要这样做我的卷曲:curl -H "Content-Type: application/json" -X POST -d '{"username":"xyz","password":"xyz"}' 172.17.0.12:3000/user/add