Awareness of cookies in JavaScript

Definition
Before the birth of the HTTPS protocol, the web browser and the server need to communicate through the HTTP protocol. The HTTP protocol is a stateless protocol. When the server and the browser complete an interaction (the browser sends a request to the server, After the server responds), the link is closed and the server forgets about the browser. Cookies were invented to allow servers to remember browsers.

When using a browser to access a certain page, some browser information can be stored in a cookie. Every time the browser sends a request to the server, the cookie will be sent to the server as part of the request, so that the server can pass the cookie to remember the information in the browser.
Cookies can only be used normally in pages started with the server. Solution: vscode installs live server
syntax

create a cookie

document.cookie = 'key = value'
document.cookie = 'qq = 123456789'
// 设置一条cookie
document.cookie = 'qq = 123456789'
document.cookie = 'password = 000000'
// 设置多条cookie

JS to modify or update the value of a cookie
The only way to modify or update a cookie value is to create a cookie with the same name to replace the cookie to be modified. Note that if the cookie to be modified defines a path attribute, the same path attribute must also be defined when modifying this attribute, otherwise a new cookie will be created. The sample code is as follows:

<script>
  // 创建一个 Cookie
  document.cookie = "url=http://c.biancheng.net/; path=/; max-age=" + 30*24*60*60;
  // 修改这个 Cookie
  document.cookie = "url=http://c.biancheng.net/javascript/; path=/; max-age=" + 365*24*60*60;
</script>

JS Delete Cookie
Deleting Cookie is similar to modifying Cookie, you only need to set the value of Cookie to empty again, and set the expires property to a past date, as shown in the following example:

<script>
  // 创建一个 Cookie
  document.cookie = "url=http://c.biancheng.net/; path=/; max-age=" + 30*24*60*60;
  // 删除这个 Cookie
  document.cookie = "url=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
</script>

Set a cookie with an expiration time
, no matter which time zone is set, it will be set according to the world standard time. Taking China as an example, it is located in the East Eighth District. If you need to set an expiration time, you need to adjust it later 8 hours, plus the desired expiration time

//例如:现在需要设置一条10秒后过期的cookie
//思路:
//1.获取当前时间
//2.将当前时间往后调整8个人小时
//3.把调整后的时间加上我们需要设置的时间

var timer = new Date()
timer.setTime(timer.getTime()-1000*60*60*8+1000*10)
document.cookie = 'vx = 00000;expires=' + timer
console.log(document.cookie)

Guess you like

Origin blog.csdn.net/weixin_48649246/article/details/127621472