express 4.0 body-parser对路由处理程序不可见

时间:2016-03-29 06:37:57

标签: javascript node.js express

我尝试通过Google POSTMAN进行如下操作

PUT /updateUser/bbb@sss.com HTTP/1.1
Host: localhost:8081
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 3f1e9857-302a-f4cf-4c24-d3222b4bc292

{"email":"bbb@sss.com", "pass":"kkk"}

当我调试req.body时未定义。这是我的代码 server.js

var express = require('express')
    , app = express()
    , mongoose = require('mongoose')
    , models = require('./models')
    , bodyParser = require('body-parser')
    , routes = require('./controllers')
    , user = require('./controllers/users.js')
    , port = 8081 //process.env.PORT || 3000

app.use(express.static(__dirname + '/public'));
app.use('/', routes);
app.use('/', user);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

module.exports = app;
mongoose.set('debug', true);
mongoose.connect('mongodb://localhost/m101JS', function (err) {
    if (err) throw err;
    console.log("mongoose connected")
    //routes(app);
    var server = app.listen(port, function () {
        var host = server.address().address
        var port = server.address().port
        console.log("RESTful Web Services listening at http://%s:%s", host, port)
    })
})

users.js

var express = require('express')
    , router = express.Router()
    , mongoose = require('mongoose')
    , User = mongoose.model('User')
    , crypto = require('crypto')
    , cleanString = require('../helpers/cleanString')
    , hash = require('../helpers/hash');
// ......    
// Update user
router.put('/updateUser/:id', function (req, res, next) {
    var email = cleanString(req.body.email);
    var pass = cleanString(req.body.pass);
    if (!(email && pass)) {
        return invalid(email);
    }

    crypto.randomBytes(16, function (err, bytes) {
        if (err) return next(err);

        var user = { _id: email };
        user.salt = bytes.toString('utf8');
        user.hash = hash(pass, user.salt);

        User.findByIdAndUpdate(req.params.id, user, function (err, post) {
            if (err) return next(err);
            res.json("updated:" + post);
        });
    });
});
module.exports = router;

它曾经在不使用路由器类时工作 旧server.js

//....
routes(app);

old users.js

module.exports = function (app) {
    app.put('/updateUser/:id', function (req, res, next) {
    .....
}

那么如何修复当前代码以使users.js可以看到正文解析器?我的意思是不必在每个文件中都要求它。

谢谢,

1 个答案:

答案 0 :(得分:6)

配置中间件的顺序在快速js中很重要。在您的配置中,您首先指定了路由器映射,然后是正文解析器中间件。您需要做的就是首先配置主体解析器,然后配置路由器映射。

表示exp:

?