gpt4 book ai didi

node.js - 在 Express 2.x 中的路由处理程序中访问 Redis

转载 作者:IT王子 更新时间:2023-10-29 06:12:12 26 4
gpt4 key购买 nike

我已经使用 CLI 创建了一个 Express 2.x 应用程序。所以我有一个路由目录和一个 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?

最佳答案

最简单的解决方案

您的 app.js 中可能有一个包含 redis 库的 require() 函数。只需将该行添加到 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 中的路由处理程序中访问 Redis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12285729/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com