node.js体系结构 - 如何共享中间件(bodyparser)

时间:2015-07-23 15:32:01

标签: node.js express body-parser

为了让'app.js'与其他功能分开,我重新构建了我的节点应用程序,如下所示:

app.js

// declare dependencies, etc
var server = http.createServer(app);

var controllers = require('./controllers');
controllers.set(app, server, passport);

控制器/ index.js

var socketController = require('./socketController.js');
var passportController = require('../config/passport.js');
var routeController = require('./routeController.js');
var routes = require('../routes');

// server side data
var sessions = [];
var userPrivileges = [];

module.exports.set = function(app, server, passport) {
    /**
     * Routes
     */
    // serve index and view partials
    app.get('/', routes.index);
    app.get('/partials/:name', routes.partials);

    // redirect all others to the index (HTML5 history)
    app.get('*', routes.index);

    routeController.set(app, passport, sessions, userPrivileges);
    socketController.set(app, server, sessions, userPrivileges);
    passportController.set(passport);
};

控制器/ routeController.js

module.exports.set = function(app, passport, sessions, userPrivileges) {

    // route to test if the user is logged in or not
    app.get('/loggedin', function(req, res) {
        res.send(req.isAuthenticated() ? req.user : '0');
    });
};

我的问题是,当我调用GET /loggedin它返回一堆HTML时 - 似乎没有激活bodyparser。我已经尝试在routeController.js中声明bodyparser,但这似乎没有帮助。我如何在这些不同的文件中共享这个中间件?

1 个答案:

答案 0 :(得分:1)

您的app.get('*', routes.index);路由在到达任何其他路线之前正在处理该请求。您可以尝试在所有其他路线之后移动该路线