1. Can the token be placed in a cookie?
When asked this question, the first thing to think about is security. Usually the answer is no, because there is a CSRF (cross-site request forgery) risk, an attacker can use the information in the cookie to send malicious requests. To solve the CSRF problem, you can set same-origin detection (Origin and Referer authentication), or set Samesite to Strict. The best thing is not to put the token in the cookie.
(One comment: 1. You said that you chose localStroage because cookies have security issues that can be attacked by xss, and later you said that local will also be attacked by xss. In fact, localStorage is vulnerable to cross-site scripting attacks (XSS), cookie Attacked by cross-site request forgery (CSRF) 2. You said that you chose localStorage because the data in localStorage will not be automatically sent to the server and can be encrypted. Doesn’t it carry the token? The cookie sets the SameSite attribute and the Secure attribute, which can control whether the cookie is automatically sent to the server with each request and whether it is only sent in the HTTPS connection, and the data stored in the cookie can also be encrypted)
2. Talk about the idea of packaging components
The flexibility, ease of use, and reusability of components should be considered. A common encapsulation idea is to perform an encapsulation on the view level, such as views with high similarity, and provide some parameters for users to modify. For those with a high degree of business reuse, extract the business components.
3. The difference between cookie and localStorage
Cookie
and LocalStorage
are two mechanisms for storing data in the browser, they have some differences in the following aspects:
- Storage capacity:
Cookie
The storage capacity of a server is usually small, andCookie
the size of each server is limited to about a fewKB
. AndLocalStorage
the storage capacity of is usually larger, generally limited to a fewMB
or so. Therefore, if a large amount of data needs to be stored,LocalStorage
it is usually more suitable; - Data sent: is automatically sent to the server on
Cookie
every request, which makes it suitable for passing data between clients and servers. And the data of is not automatically sent to the server, it only stores data on the browser side, so it is suitable for sharing data between different pages under the same domain name;HTTP
Cookie
localStorage
LocalStorage
- Lifecycle:
Cookie
You can set an expiration time, so that the data will automatically expire after the specified time. AndLocalStorage
the data of will be permanently stored in the browser unless manually deleted through JavaScript code; - Security:
Cookie
The security is low, because it will be automatically sent to the serverCookie
in eachHTTP
request, and there is a risk of being stolen or tampered with. The data ofLocalStorage
is only stored on the browser side and will not be automatically sent to the server, which is relatively safer