Cookie localStorage sessionStorage的異同
以下來自:詳說 Cookie, LocalStorage 與 SessionStorage
特性 | Cookie | localStorage | sessionStorage |
---|---|---|---|
應用 | 身份標識 | 存儲數據 | 存儲數據 |
數據的生命周期 | (一般由服務器生成)可自由設置失效時間。 | 數據持久化 | 存在于一次session會話,關閉頁面后銷毀 |
數據結構 | 鍵值對的集合 | 鍵值對的集合 | 鍵值對的集合 |
存放數據 | 每條4KB,一般50條(IE6 20),客戶端最多300條 | 一般為5MB | 同(localStorage) |
存放位置 | 客戶端 | 客戶端 | 客戶端 |
作用域 | (可設置)本域和任何父域 | 在所有同源窗口中共享 | 當前會話窗口 |
與服務器端通信 | 攜帶在HTTP頭中參與通信,影響請求響應時間 | 僅存在于客戶端(即瀏覽器)中,不參與通信 | 同(localStorage) |
數據提交 | 被動(全部提交) | 主動(選擇性) | 主動(選擇性) |
安全性 | 明文(不安全) | 明文(不安全) | 明文(不安全) |
1、Cookie
1、Cookie是在RFC2109里初次被提及,是為了辨別用戶信息而存儲在客戶端的數據。
2、每個客戶端最多保持300個Cookie,每個域名下一般為50個(IE 6僅20個)
3、每個Cookie最多存儲最多4KB
4、Cookie的信息每次發起請求都會隨請求頭提交給服務器
5、Cookies 使用不同的源定義方式。一個頁面可以為本域和任何父域設置cookie,只要是父域不是公共后綴(public suffix)即可。Firefox 和 Chrome 使用 Public Suffix List 決定一個域是否是一個公共后綴(public suffix)。Internet Explorer使用其自己的內部方法來確定域是否是公共后綴。不管使用哪個協議(HTTP/HTTPS)或端口號,瀏覽器都允許給定的域以及其任何子域名(sub-domains) 訪問 cookie。設置 cookie 時,你可以使用Domain,Path,Secure,和Http-Only標記來限定其訪問性。讀取 cookie 時,不會知曉它的出處。 即使您僅使用安全的https連接,您看到的任何cookie都可能使用不安全的連接進行設置。
1、客戶端設置Cookie(HTTP響應中)
Set-cookie:name='...name';expires='...date';path='...path';domain='...domain'
支持Cookie的瀏覽器將創建Cookie文件并保存(也可能是寫入內存中)。用戶
每次發起請求時瀏覽器根據條件過濾(expires path)后加入請求頭響應:
請求頭:Cookie: name='...name';Path='.../path'
2、Node中設置Cookie(response中提供了原生方法):
res.cookie(name, value [, options]);
name: 類型為String
value: String或Object(自動序列化,JSON.stringify(obj))
Option:Object
Option包含:
domain:String, //有效域名,默認網站域名
expires:Date, //過期時間,沒有設置或為0,瀏覽器關閉后清除(當前session有效)
httpOnly: Boolean, //只能被WEB server訪問
maxAge:String, // 類似expires 過期時間
path:String,//有效路徑,默認'/'
secure:Boolean, //只能被https使用,默認false
singed:Boolean //使用簽名,默認false(express ,cookie-parse ->> req.secret)
3、Koa中使用Cookie
ctx.cookies.get(name, [, options]) //獲取
ctx.cookies.set(name, value, [options]) //設置
2、Session
Session(主要用來管理會話)是一種概念,表示用戶從進入到離開網絡應用這段時間內產生的動作以及上下文
1、HTTP中的Session
Cookie每次請求都隨著HTTP發送給服務器,給每個Cookie一個唯一的ID用來記錄用戶
2、Session的步驟
1)生成SessionId
2)SessionId寫入內存(一旦服務器斷電或重啟就會丟失,--redis持久化...)
3)將帶有SessionId的Cookie發送給客戶端
3、Koa中使用Session (koa-session)
const Koa = require('koa')
const session = require('koa-session')
const app = new Koa()
...
app.keys = ['secret key']
const CONFIG = {
key: 'login', /** (string) cookie key (default is koa:sess) */
/** (number || 'session') maxAge in ms (default is 1 days) */
/** 'session' will result in a cookie that expires when session/browser is closed */
/** Warning: If a session cookie is stolen, this cookie will never expire */
maxAge: 86400000, // (number) maxAge in ms (default is 1 days)
overwrite: true, /** (boolean) can overwrite or not (default true) */
httpOnly: true, /** (boolean) httpOnly or not (default true) */
signed: true, /** (boolean) signed or not (default true) */
rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
};
app.use(session(CONFIG, app))
....
router.get('/login', (ctx, next) => {
ctx.session.login = true
...
})
...
3、localStorage 與 sessionStorage (HTML5 Web Storage)
HTML web storage; better than cookies.
What is HTML Web Storage?
With web storage, web applications can store data locally within the user's browser.
Before HTML5, application data had to be stored in cookies, included in every server request. Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
Web storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.
Browser Support
The numbers in the table specify the first browser version that fully supports Web Storage.
IE | Firefox | Chrome | Safari | Opera | |
---|---|---|---|---|---|
localStorage | 8.0 | 3.5 | 4.0 | 4.0 | 11.5 |
sessionStorage | 8.0 | 2.0 | 5.0 | 4.0 | 11.5 |
HTML Web Storage Objects
HTML web storage provides two objects for storing data on the client:
window.localStorage - stores data with no expiration date
window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)
Before using web storage, check browser support for localStorage and sessionStorage:
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}
The localStorage Object
The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
The sessionStorage Object
The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.
The following example counts the number of times a user has clicked a button, in the current session:
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
Web Storage帶來的好處
以下來自:
請描述一下 cookies,sessionStorage 和 localStorage 的區別
減少網絡流量:一旦數據保存在本地后,就可以避免再向服務器請求數據,因此減少不必要的數據請求,減少數據在瀏覽器和服務器間不必要地來回傳遞。
快速顯示數據:性能好,從本地讀數據比通過網絡從服務器獲得數據快得多,本地數據可以即時獲得。再加上網頁本身也可以有緩存,因此整個頁面和數據都在本地的話,可以立即顯示。
臨時存儲:很多時候數據只需要在用戶瀏覽一組頁面期間使用,關閉窗口后數據就可以丟棄了,這種情況使用sessionStorage非常方便。