在Express 2.x中访问Redis insdie路由处理程序
我已经使用CLI创build了一个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?
最简单的解决scheme
你可能有一个require()函数,在你的app.js中包含一个redis库。 只需要将该行添加到index.js文件的顶部即可。
如果您正在使用node_redis模块,只需包含以下内容:
var redis = require("redis"), client = redis.createClient();
替代方法
如果您正在寻找重用现有连接,请尝试将client
variables传递给index.js中的函数:
app.js
app.post('/signup', routes.myroute(client));
index.js
exports.myroute = function(client) { // client can be used here }
您正在使用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 }));
现在,连接会话魔术会将会话详细信息放在传递到每个路由的“req”对象上。 这样,你不需要通过redis客户端遍地。 让req对象为你工作,让你在每个路由处理程序中免费得到它。
确保你做了一个:npm install connect-redis