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

僤鯓⒐⒋嵵緔 提交于 2020-01-23 11:58:20

问题


While using express.js for handling various routes I want to encapsulate all of my route code in a seperate 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 seperate 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


回答1:


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.




回答2:


TJ Holowaychuk made some great examples for express on the github page, here's the one about route separation:

https://github.com/visionmedia/express/tree/master/examples/route-separation



来源:https://stackoverflow.com/questions/5702509/how-is-req-and-res-accessible-accross-modules-in-express-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!