react, cookie, storage, font end,

Cookies与Storage的小试与比较

DolorHunter DolorHunter Follow May 02, 2021 · 2 mins read
Cookies与Storage的小试与比较
Share this

后端数据库获取数据的条件通常都是ID,查找用ID,修改用ID,删除还是用ID。因此,在网页前端登录后,会根据用户名查找ID,并且记录下用户名或ID,或两者以便之后的查询。

根据查找到的资料,能够存储此资料有三个地方:Cookies,SessionStorage 和 LocalStorage。其中最常存储数据的位置是Cookies,例如GitHub在Cookies中存储了用户名,Twitter存储了用户ID。

虽然我用的是React,但是在依赖上还是选择了 js-cookie/js-cookie 而不是 react-cookie,因为看起来更加的简洁。当然,cookie也不止这两个包,但是应该都是互相封装的(猜测原因是昨天每个cookie包都用不了,只能用document.cookie写,今天突然又能用了)。

文档相对react-cookie也解释的也很清楚,后者的功能太多了反倒有点眼花缭乱。并且因为我的项目大部分使用的是hook,就要用useCookies;但有一部分有是js,就要用get/set/remove。一个Cookie,两个用法,两个风格,看起来就不太舒服。

js-cookie基础示例

js-cookie/js-cookie 文档中的基础示例:

import cookie from 'js-cookie';

cookie.set('foo', 'bar');

cookie.set('name', 'value', { expires: 7, path: '' });

cookie.get('name'); // => 'value'

cookie.remove('name');

cookie.remove('name', { path: '', domain: '.yourdomain.com' });

cookie 主要就三种用法,set/get/remove。其中,option内的参数有:

参数
Expires date
Max-Age non-zero-digit
Domain domain-value
Path path-value
Secure true/false
HttpOnly true/false
SameSite Strict/Lax/None

其实我刚一开始用的是 LocalStorage 做uuid和username存储,跟(调用依赖下的)cookie使用上来说差不多,方法为 getItem/setItem/removeItem。但是爬帖子发现混用存储不太好,就改成了cookie,甚至把登录标记的id_token也从localStoage改成了cookie。

Cookies,SessionStorage 和 LocalStorage异同

Cookies and local storage serve different purposes. Cookies are primarily for reading server-side, local storage can only be read by the client-side. So the question is, in your app, who needs this data — the client or the server?

If it’s your client (your JavaScript), then by all means switch. You’re wasting bandwidth by sending all the data in each HTTP header.

If it’s your server, local storage isn’t so useful because you’d have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.

You’ll want to leave your session cookie as a cookie either way though.

As per the technical difference, and also my understanding:

  1. Apart from being an old way of saving data, Cookies give you a limit of 4096 bytes (4095, actually) — it’s per cookie. Local Storage is as big as 5MB per domain — SO Question also mentions it.

  2. localStorage is an implementation of the Storage Interface. It stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data — unlike cookie expiry.

-StackOverflow - Local Storage vs Cookies

  • LocalStorage就是客户端本地的存储,只能由客户端利用js读取。
  • SessionStorage相对LocalStorage,在不同页面中数据不互通,关闭网页会话后自动清除。
  • Cookies主要用于在通信中携带信息,可能用于服务器的安全验证。但是会增加流量,并且是明文传输。

但是因为我的项目使用axios(类ajax)post方法进行通信,服务器也没有验证登录,因此从请求角度使用Cookies与LocalStorage差异并不大(虽然两个东西的设计初衷不一样)。我能感知到的唯一区别就是数据存储的大小与cookie的option上。

参考资料:

Join Newsletter
Get the latest news right in your inbox. We never spam!
DolorHunter
Written by DolorHunter
Developer & Independenet Blogger