如何在Express.js中的模块之间访问req和res [英] How is req and res accessible accross modules in Express.js

查看:136
本文介绍了如何在Express.js中的模块之间访问req和res的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用express.js处理各种路由时,我想将所有路由代码封装在一个单独的模块中,但是如何在模块之间访问req和res对象,请参见下面的代码
主文件examples.js编写如下

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);

我想要的是将登录处理代码编写在名为login.js的单独模块/文件中,那么问题是如何在login.js中访问响应对象。我认为以下代码将无法正常工作,因为无法解析req和res的类型。

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

因此,当我使用节点example.js启动服务器时,出现错误

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

无法调用未定义的方法发送

'Cannot call method send of undefined'

Request和REsponse对象如何通过模块传递

How is the Request and REsponse objects passed along modules

推荐答案

这应该有效:

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

您的示例试图传递 login.auth <的返回值/ code>用作请求的获取处理程序。上面的代码改为通过 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.

这篇关于如何在Express.js中的模块之间访问req和res的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆