Search code examples
node.jsexpressnode.js-connect

How is req and res accessible accross modules in Express.js?


While using express.js for handling various routes I want to encapsulate all of my route code in a separate module, but how can I access the req and res object across modules? See the code below. The main file examples.js is written as follows:

var app = require('express').createServer();
var login = require('./login.js');
app.get('/login', login.auth(app.req, app.res));
app.listen(80);

What I want is that the login handling code be written in a separate module/file called login.js. The question then is how will the response object be accessible in login.js? I think the following code will not work as because the type of req and res is not resolved.

exports.auth = function(req, res) {
    res.send('Testing');
}

Hence when I start the server with node example.js I get the error:

'Cannot call method send of undefined'

How is the Request and Response objects passed along modules?


Solution

  • This should work:

    app.get('/login', login.auth);
    

    Your example was attempting to pass the return value of the login.auth function as get handler for the request. The above instead passes the login.auth function itself as the handler.