簡(jiǎn)述Cookie Session localStorage sessionStorage

Cookie localStorage sessionStorage的異同

以下來(lái)自:詳說(shuō) Cookie, LocalStorage 與 SessionStorage

特性 Cookie localStorage sessionStorage
應(yīng)用 身份標(biāo)識(shí) 存儲(chǔ)數(shù)據(jù) 存儲(chǔ)數(shù)據(jù)
數(shù)據(jù)的生命周期 (一般由服務(wù)器生成)可自由設(shè)置失效時(shí)間。 數(shù)據(jù)持久化 存在于一次session會(huì)話,關(guān)閉頁(yè)面后銷毀
數(shù)據(jù)結(jié)構(gòu) 鍵值對(duì)的集合 鍵值對(duì)的集合 鍵值對(duì)的集合
存放數(shù)據(jù) 每條4KB,一般50條(IE6 20),客戶端最多300條 一般為5MB 同(localStorage)
存放位置 客戶端 客戶端 客戶端
作用域 (可設(shè)置)本域和任何父域 在所有同源窗口中共享 當(dāng)前會(huì)話窗口
與服務(wù)器端通信 攜帶在HTTP頭中參與通信,影響請(qǐng)求響應(yīng)時(shí)間 僅存在于客戶端(即瀏覽器)中,不參與通信 同(localStorage)
數(shù)據(jù)提交 被動(dòng)(全部提交) 主動(dòng)(選擇性) 主動(dòng)(選擇性)
安全性 明文(不安全) 明文(不安全) 明文(不安全)

1、Cookie

1、Cookie是在RFC2109里初次被提及,是為了辨別用戶信息而存儲(chǔ)在客戶端的數(shù)據(jù)。

2、每個(gè)客戶端最多保持300個(gè)Cookie,每個(gè)域名下一般為50個(gè)(IE 6僅20個(gè))

3、每個(gè)Cookie最多存儲(chǔ)最多4KB

4、Cookie的信息每次發(fā)起請(qǐng)求都會(huì)隨請(qǐng)求頭提交給服務(wù)器
5、Cookies 使用不同的源定義方式。一個(gè)頁(yè)面可以為本域和任何父域設(shè)置cookie,只要是父域不是公共后綴(public suffix)即可。Firefox 和 Chrome 使用 Public Suffix List 決定一個(gè)域是否是一個(gè)公共后綴(public suffix)。Internet Explorer使用其自己的內(nèi)部方法來(lái)確定域是否是公共后綴。不管使用哪個(gè)協(xié)議(HTTP/HTTPS)或端口號(hào),瀏覽器都允許給定的域以及其任何子域名(sub-domains) 訪問(wèn) cookie。設(shè)置 cookie 時(shí),你可以使用Domain,Path,Secure,和Http-Only標(biāo)記來(lái)限定其訪問(wèn)性。讀取 cookie 時(shí),不會(huì)知曉它的出處。 即使您僅使用安全的https連接,您看到的任何cookie都可能使用不安全的連接進(jìn)行設(shè)置。

鏈接:跨源網(wǎng)絡(luò)訪問(wèn)

1、客戶端設(shè)置Cookie(HTTP響應(yīng)中)

Set-cookie:name='...name';expires='...date';path='...path';domain='...domain'

支持Cookie的瀏覽器將創(chuàng)建Cookie文件并保存(也可能是寫入內(nèi)存中)。用戶

每次發(fā)起請(qǐng)求時(shí)瀏覽器根據(jù)條件過(guò)濾(expires path)后加入請(qǐng)求頭響應(yīng):

請(qǐng)求頭:Cookie: name='...name';Path='.../path'

2、Node中設(shè)置Cookie(response中提供了原生方法):

res.cookie(name, value [, options]);

name: 類型為String

value: String或Object(自動(dòng)序列化,JSON.stringify(obj))

Option:Object

Option包含:

domain:String, //有效域名,默認(rèn)網(wǎng)站域名

expires:Date, //過(guò)期時(shí)間,沒(méi)有設(shè)置或?yàn)?,瀏覽器關(guān)閉后清除(當(dāng)前session有效)

httpOnly: Boolean, //只能被WEB server訪問(wèn)

maxAge:String, // 類似expires 過(guò)期時(shí)間

path:String,//有效路徑,默認(rèn)'/'

secure:Boolean, //只能被https使用,默認(rèn)false

singed:Boolean //使用簽名,默認(rèn)false(express ,cookie-parse ->> req.secret)

3、Koa中使用Cookie

ctx.cookies.get(name, [, options]) //獲取

ctx.cookies.set(name, value,  [options]) //設(shè)置

image

2、Session

Session(主要用來(lái)管理會(huì)話)是一種概念,表示用戶從進(jìn)入到離開(kāi)網(wǎng)絡(luò)應(yīng)用這段時(shí)間內(nèi)產(chǎn)生的動(dòng)作以及上下文


1、HTTP中的Session

Cookie每次請(qǐng)求都隨著HTTP發(fā)送給服務(wù)器,給每個(gè)Cookie一個(gè)唯一的ID用來(lái)記錄用戶

2、Session的步驟

1)生成SessionId

2)SessionId寫入內(nèi)存(一旦服務(wù)器斷電或重啟就會(huì)丟失,--redis持久化...)

3)將帶有SessionId的Cookie發(fā)送給客戶端

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帶來(lái)的好處

以下來(lái)自:
請(qǐng)描述一下 cookies,sessionStorage 和 localStorage 的區(qū)別
減少網(wǎng)絡(luò)流量:一旦數(shù)據(jù)保存在本地后,就可以避免再向服務(wù)器請(qǐng)求數(shù)據(jù),因此減少不必要的數(shù)據(jù)請(qǐng)求,減少數(shù)據(jù)在瀏覽器和服務(wù)器間不必要地來(lái)回傳遞。
快速顯示數(shù)據(jù):性能好,從本地讀數(shù)據(jù)比通過(guò)網(wǎng)絡(luò)從服務(wù)器獲得數(shù)據(jù)快得多,本地?cái)?shù)據(jù)可以即時(shí)獲得。再加上網(wǎng)頁(yè)本身也可以有緩存,因此整個(gè)頁(yè)面和數(shù)據(jù)都在本地的話,可以立即顯示。
臨時(shí)存儲(chǔ):很多時(shí)候數(shù)據(jù)只需要在用戶瀏覽一組頁(yè)面期間使用,關(guān)閉窗口后數(shù)據(jù)就可以丟棄了,這種情況使用sessionStorage非常方便。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容