2012-09-05 101 views
1

我使用CLI創建了Express 2.x應用程序。所以我有一個路由目錄和一個index.js。 現在,在app.js中,我已連接到Redis,並且它正常工作。在Express 2.x中訪問Redis插件路由處理程序

我從這裏app.js調用路由/ index.js文件中的函數:

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

的myroute函數包含代碼從Redis的一個關鍵。

現在,我得到的錯誤是沒有定義redis。 如何將redis對象從app.js傳遞到routes/index.js?

回答

1

最簡單的解決

你可能有一個require()函數,包括在你的app.js.一個Redis的LIB只需將該行添加到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 
} 
+0

嘿嘿,謝謝... 它的工作原理... 我只是想知道,它連接到Redis的服務器再次,或使用現有連接以避免太多的開銷? –

+0

並且沒有其他方法可以直接將redis對象傳遞給路由嗎? –

+0

那麼,節點模塊一旦被加載就被緩存,所以沒有開銷......但實際的連接可能是新的。使用可重複使用連接的替代解決方案更新答案 – Kostia

1

您使用快遞,這樣連接,所以利用連接中間件。特別是會話中間件。 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安裝連接,Redis的

相關問題