2017-06-30 90 views
0

我想在我的Express後端使用client-sessions模塊。所以,我已經安裝了模塊,並設置了快遞的工作是這樣的:ExpressJS客戶端會話不保存會話

var sessions  = require('client-sessions'); 
app.use(sessions({ 
    cookieName: Constants.CLIENT_SESSION_NAME, // pi_client_session 
    secret: Constants.CLIENT_SESSION_SECRET, // some long string here 
    duration: Constants.CLIENT_SESSION_LIFETIME // 24 * 60 * 60 * 1000; 
})); 

但是,出於某種原因,它在每次請求空。這裏的例子:

router.get('/auth', function(req, res, next) { 
    console.log("CLIENT SESSION BEFORE: " + JSON.stringify(req[Constants.CLIENT_SESSION_NAME])); 
    req[Constants.CLIENT_SESSION_NAME].test = "saved"; 
    console.log("CLIENT SESSION AFTER: " + JSON.stringify(req[Constants.CLIENT_SESSION_NAME])); 
    return res.json({ sessionSaved: true}); 
} 

這裏是輸出我得到每次:

CLIENT SESSION BEFORE: {} 
CLIENT SESSION AFTER: {"test":"saved"} 

我從谷歌Chrome,歌劇嘗試。結果相同。

我的設置是這樣的:ReactJS應用程序代理從localhost:3000到localhost:3001這是我的快遞後端。 我試過用郵差表達直接請求,並正常保存會話。所以這個問題肯定存在於從反應到表達和回來的過程中。 上反應的身邊我的package.json文件如下(我沒有包括依賴):

"scripts": { 
    "build-css": "node-sass-chokidar src/ -o src/", 
    "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", 
    "start-js": "react-scripts start", 
    "start": "npm-run-all -p watch-css start-js", 
    "build": "npm run build-css && react-scripts build", 
    "eject": "react-scripts eject" 
    }, 
    "proxy": "http://localhost:3001" 

因此問題是,如何才能得到使用代理這樣的客戶端會話?

+1

你確定客戶端請求正確傳遞憑據?您應該檢查a)客戶是否收到會話cookie,以及b)客戶是否在隨後的請求中發送該cookie。另外,看看這裏:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials – robertklep

+0

我忘了提及,我使用fetch(),而不是XMLHttpRequest。但感謝指向我的關鍵字憑據:)。我會嘗試使用提取來檢查 – Konstantin

+1

這同樣適用,只是略有不同:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Sending_a_request_with_credentials_included – robertklep

回答

1

因爲你作出反應的應用程序是在一個不同的起源比你的後臺運行,你需要明確地告訴fetch通過與每個請求的憑據(如餅乾):

fetch('http://your-backend', { 
    credentials: 'include' 
}).then(...)