我已经使用 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/