Express.js 中如何跨模块访问 req 和 res?
在使用express.js处理各种路由时,我想将所有路由代码封装在一个单独的模块中,但是如何跨模块访问req和res对象?请参阅下面的代码。 主文件examples.js 编写如下:
var app = require('express').createServer();
var login = require('./login.js');
app.get('/login', login.auth(app.req, app.res));
app.listen(80);
我想要的是将登录处理代码编写在名为login.js 的单独模块/文件中。那么问题是如何在 login.js 中访问响应对象?我认为以下代码将不起作用,因为 req 和 res 的类型未解析。
exports.auth = function(req, res) {
res.send('Testing');
}
因此,当我使用节点 example.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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该可行:
您的示例尝试将
login.auth
函数的返回值作为请求的获取处理程序传递。上面的代码将login.auth
函数本身作为处理程序传递。This should work:
Your example was attempting to pass the return value of the
login.auth
function as get handler for the request. The above instead passes thelogin.auth
function itself as the handler.TJ Holowaychuk 在 github 页面上制作了一些很棒的 Express 示例,这是关于路由分离的示例:
https://github.com/visionmedia/express/tree/master/examples/route-separation
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