node.js - 在 Express 2.x 中的 Route Handler 中访问 Redis

标签 node.js routes express redis

我已经使用 CLI 创建了一个 Express 2.x 应用程序。所以我有一个routes目录和一个index.js。 现在,在app.js中,我已经连接到Redis,并且它可以正常工作。

我在这里从app.js调用routes/index.js文件中的函数:

app.post('/signup', routes.myroute);

myroute 函数包含从 Redis 获取 key 的代码。

现在,我收到 redis 未定义的错误。 如何将redis对象从app.js传递到routes/index.js?

最佳答案

最简单的解决方案

您可能有一个 require() 函数,其中包含 app.js 中的 redis 库。只需将该行添加到您的 index.js 文件的顶部即可。

如果您使用的是node_redis模块,只需包含以下内容:

var redis = require("redis"),
client = redis.createClient();


替代方法

如果您希望重用现有连接,请尝试将 client 变量传递给 index.js 中的函数:

app.js

app.post('/signup', routes.myroute(client));

index.js

exports.myroute = function(client) {
    // client can be used here
}

关于node.js - 在 Express 2.x 中的 Route Handler 中访问 Redis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12285729/

相关文章:

.htaccess - Backbone.js PushState routes .htaccess 仅作为散列工作,但无处可寻

node.js - OpenMCT 的 "npm install"给出很多错误

node.js - 尝试访问 DynamoDB 时 AWS Lambda node.js 超时

c# - 性能:System.Diagnostics.Process 与 System.Management.Automation.PowerShell

node.js - npm install 导致 'ENOENT: no such file or directory'

javascript - config/routes.js 中定义的路由出现 404(未找到)错误

azure - 如何根据 NGINX 入口 Controller 中的源 IP 地址使用 if 条件路由流量

javascript - 仅当文档与数据库不同时才更新文档?

javascript - Multer 使用数据创建新文件夹

express - Angular2.0 路由器适用于组件而不是模块?