簡述Cookie Session localStorage sessionStorage

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]) //設置

image

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非常方便。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,565評論 6 539
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,115評論 3 423
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,577評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,514評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,234評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,621評論 1 326
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,641評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,822評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,380評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,128評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,319評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,879評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,548評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,970評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,229評論 1 291
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,048評論 3 397
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,285評論 2 376

推薦閱讀更多精彩內容