2016-11-15 49 views
1

我想構建一個基本的登錄功能,並測試它創建一個會話,我可以稍後使用。我正在使用express-session和redis來保存會話數據。這裏是我的設置:請求cookie不返回按預期方式快速會話數據

app.use(bodyParser.json()) 
app.use(bodyParser.urlencoded({extended: true})) 
app.use(express.static(path.join(__dirname, 'client/build'))) 

app.use(cookieParser(process.env.COOKIE_SECRET)) 
app.use(session({ 
    store: new redisStore({ 
    host: '127.0.0.1', 
    port: 6379 
    }), 
    secret: process.env.SESSION_SECRET, 
    cookie: {maxAge: 1800}, 
    name: 'appName', 
    resave: false, 
    saveUninitialized: false 
})) 

app.use('/', routes) 

然後我登錄路由:

router.post('/api/login', (req, res) => { 
    req.session.userId = req.body.id 
    req.session.email = req.body.email 

    //do I need to send out a cookie with the session created here? 
    res.set({'Set-Cookie': 'appSession=' + req.session.id}) 
    res.status(200).send({ 
    "message": `User ${req.body.id} logged in with cookie ${req.session.id}` 
    }) 
}) 

然後,它是我的理解,我應該能夠讀取並加入到這個會話在那裏我將cookie發送回的任何請求。這是我的API來測試:

router.post('/api/test' (req, res) => { 
    if(req.session && req.session.userId) { 
    res.status(200).send({"message": `User ID ${req.session.userId} is authenticated`}) 
    } else { 
     res.status(401).send({"message": `User ID ${req.session.id} is not authenticated`}) 
    } 
}) 

我發送給使用郵差用頭Cookie: appName=${sessionID}使用在api/login路線創建的會話ID這個API的請求。這總是創建一個新的sessionId並返回401.

我的理解是否正確?如果是這樣,我該如何創建這種預期的行爲?

回答

1

我現在已經得到了一個答案 - 在互聯網上有一些我並不認爲清楚的東西。

首先,它是有用的,如果您有任何關於express-session麻煩,用DEBUG=express-session node server.js

運行的服務器當我這樣做,我意識到express-session沒有找到創建的會話調試問題。這是因爲我在幾秒鐘內設置了maxAge屬性,而不是毫秒,因此它立即過期。白癡。

還有一個問題。我試圖以檢索會話時下列調試輸出:

express-session cookie unsigned +1ms 
    express-session no SID sent, generating session +1ms 

這是該cookie解析器沒有找到我的SessionID,因爲cookie解析器需要使用相同的密鑰爲express-session。再次,回想起來非常明顯。

希望這可以幫助那些得到相同錯誤的人。