简体   繁体   中英

node.js architecture - how to share middleware (bodyparser)

To keep 'app.js' separated from other functionality I've restructured my node application like so:

app.js

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

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

controllers/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);
};

controllers/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');
    });
};

My problem is when I call GET /loggedin it's returning a bunch of HTML - it seems like bodyparser is not being activated. I've tried declaring bodyparser in routeController.js but that hasn't seemed to help. How would I share this middleware across these different files?

Your app.get('*', routes.index); route is handling the request before it ever gets to any other routes. You might try moving that route after all other routes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM