SoFunction
Updated on 2025-04-10

Common operations and attribute introduction based on cookies

Overview

Recently, the project needs to use cookies to store some user information; I have studied it and shared it

A cookie is a small piece of text information saved by the server in the browser. The size of each cookie cannot exceed 4KB. Every time the browser makes a request to the server, this message will be automatically attached.

Set cookie storage

 = 'userName=fengkaicahng';

Note: Setting cookies can only be stored one at a time

Cookies can be set multiple times. The key will not be reassigned but will create a new cookie.

Read cookies

var allCookies = ;

//Read all cookie strings at once//So we usually have to make a conversion
var cookiesArray = (';');

 (cookiesArray);

Several attributes of cookies

value (must) a key-value pair to specify the value of the cookie

 = 'userName=fengkaicahng';

expires Specifies the expiration time of the cookie; the format is ()

var day = new Date();
 (()+(1*24*60*60*1000));

//Set the validity period of one day//If not set; the default time is that the current session window is closed and invalid
 = 'userName=fengkaicahng;expires="+day+"';

domain Specifies the domain name to send the cookie

 var day = new Date();
 (()+(1*24*60*60*1000));

//Cookies are only sent under this domain name,//If not set; the default is the domain name when setting cookies//The following configuration will take effect under all subdomains
 = 'userName=fengkaicahng;expires='+day+';domain=;

path Specify the path to the cookie

var day = new Date();
 (()+(1*24*60*60*1000));

//Cookies can be sent only if this path is the same as the path sent to the server. You can directly configure it/match from the root directory. This match is not absolute.//If not set; the default is the path when requesting the cookie//The following configuration will take effect under all request paths//Note that the prerequisite for path to take effect is that domain matches successfully, otherwise it will be nonsense.

 = 'userName=fengkaicahng;expires='+day+';domain=;path=/'

Secure Specifies that cookies can only be sent to the server under the encryption protocol HTTPS

var day = new Date();
 (()+(1*24*60*60*1000));

//The value of this property is a boolean value//If this communication protocol is HTTPS, the protocol will be automatically opened//If set manually, the configuration will not be sent under normal HTTP protocol
 = 'userName=fengkaicahng;expires='+day+';domain=;path=/;secure=true'

The above article is based on common operations and attribute introductions based on cookies. I hope it can give you a reference and I hope you can support me more.