express-session 的使用:
1.安裝 express-session
cnpm install express-session --save
2.引入 express-session
var session = require("express-session");
3.設(shè)置官方文檔提供的中間件
app.use(session({
secret: 'keyboard cat',
esave: true,
saveUninitialized: true
}))
上述也是官方文檔中的內(nèi)容,沒有過多需要說明的。在配置好上述功能后,我發(fā)現(xiàn)通過前臺(tái)訪問始終無法獲取到req.session中存儲(chǔ)的用戶狀態(tài)值(req.session.username='123',可在登錄方法下設(shè)置session值記錄)。
通過打印session.id,發(fā)現(xiàn)每次請(qǐng)求都會(huì)新建一個(gè)session,每次的session.id都會(huì)變,所以無法獲取。因此我們需要在前端(我的是vue)中配置withCredentials為true(這里主要是通過讓前端請(qǐng)求攜帶cookie訪問,來辨別訪問是否是一個(gè),具體原理不再介紹)。我的vue中利用了axios所以,在axios中加入:
// 創(chuàng)建axios實(shí)例
const service = axios.create({
withCredentials:true,
baseURL: process.env.BASE_API, // api的base_url
timeout: 5000 // 請(qǐng)求超時(shí)時(shí)間
})
此時(shí),發(fā)起訪問會(huì)在后臺(tái)提示跨域錯(cuò)誤。
Failed to load [http://pre.api.jmxy.mockuai.c...](http://pre.api.jmxy.mockuai.com/jml/auth/session_token/get?format=json&app_key=e83a211ec1645e51c84506c065e3379b&time=1541350006&app_version=2.5.0&device_id=admin&phone_model=chrome&system_version=69.0.3497.100&api_sign=d87a54ca220f9f15233cf0e015ebb201): The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin '[http://pre.promotion.jmxy.moc...](http://pre.promotion.jmxy.mockuai.com/)' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
在后臺(tái)的跨域中設(shè)置origin不為'*',且設(shè)置頭部withCredentials為true即可。我后臺(tái)跨域使用了CORS組件,配置代碼如下:
exports.proxy ={
origin:'http://localhost:9528',
methods:['GET','POST'],
alloweHeaders:['Conten-Type', 'Authorization'],
credentials:true,
}