1

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

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

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

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

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

4

2 回答 2

1

最简单的解决方案

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

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

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


替代方法

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

应用程序.js

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

index.js

exports.myroute = function(client) {
    // client can be used here
}
于 2012-09-05T16:23:51.497 回答
1

您使用的是 Express,因此使用的是 Connect,因此请使用 Connect 中间件。特别是会话中间件。Connect 的会话中间件具有存储的概念(存储会话内容的地方)。该存储可以在内存中(默认)或数据库中。因此,使用 redis 存储 (connect-redis)。

var express = require('express'),
    RedisStore = require('connect-redis')(express),
util = require('util');

var redisSessionStoreOptions = {
    host: config.redis.host, //where is redis
    port: config.redis.port, //what port is it on
    ttl: config.redis.ttl, //time-to-live (in seconds) for the session entry
    db: config.redis.db //what redis database are we using
}

var redisStore = new RedisStore(redisSessionStoreOptions);
redisStore.client.on('error', function(msg){
    util.log('*** Redis connection failure.');
    util.log(msg);
    return;
});
redisStore.client.on('connect', function() {
    util.log('Connected to Redis');
});

app = express();

app.use(express.cookieParser());  
app.use(express.session({ 
        store: redisStore, 
        cookie: {   path: '/', 
                    httpOnly: true, //helps protect agains cross site scripting attacks - ie cookie is not available to javascript
                    maxAge: null }, 
        secret: 'magic sauce',  //
        key: 'sessionid' //The name/key for the session cookie
    }));

现在,Connect 会话魔术将会话详细信息放在传递到每个路由的“req”对象上。这样,您不需要到处传递 redis 客户端。让 req 对象为您工作,因为无论如何您都可以在每个路由处理程序中免费获得它。

确保你做了: npm install connect-redis

于 2012-09-05T23:41:35.053 回答