本系列文章是本人學習相關知識時所積累的筆記,以記錄自己的學習歷程,也爲了方便回顧知識;故文章內容較爲隨意簡練,抱着學習目的來的同學務必轉移他處,以免我誤人子弟~
cookies用途
Koa中使用cookies模塊,封裝獲取前端請求的cookie和後端要求前端存儲cookie的功能;
app.use(async (ctx) => {
// 設置cookie,前端接收到響應後將cookie存放本地
ctx.cookies.set(
'cookieName',
'cookieValue',
{
domain: 'localhost', // 寫cookie所在的域名
path: '/index', // 寫cookie所在的路徑
maxAge: 10 * 60 * 1000, // cookie有效時長
expires: new Date('2020-02-15'), // cookie失效時間
httpOnly: false, // 是否只用於http請求中獲取
overwrite: false // 是否允許重寫
}
)
// 獲取前端請求中名稱爲“otherCookieName”的cookie值
ctx.cookies.get("otherCookieName");
})
cookies函數原理
keygrip模塊
js操作符:
^
異或
規則:位不相同時才爲1;
//http://codahale.com/a-lesson-in-timing-attacks/
var constantTimeCompare = function(val1, val2){
if(val1 == null && val2 != null){
return false;
} else if(val2 == null && val1 != null){
return false;
} else if(val1 == null && val2 == null){
return true;
}
if(val1.length !== val2.length){
return false;
}
var result = 0;
for(var i = 0; i < val1.length; i++){
result |= val1.charCodeAt(i) ^ val2.charCodeAt(i); //Don't short circuit
}
return result === 0;
};