The practice of cookie in front end

Time:2020-2-27

The theme of this article is to build a service with node.js to see the actual application scenarios of cookies

Environmental configuration

Let’s create a new filemain.jsAnd inmain.jsWrite the following code:

const express = require('express')
const app = express()

app.listen(3000, err => {
  if (err) {
    return console.log(err)
  }
  Console. Log ('---- open http: // localhost: 3000 ----')
})

app.get('/', (req, res) => {
  res.send('<h1>hello world!</h1>')
})
node main.js

//A local service is running. Now open http: // localhost: 3000
//You can see a big Hello world!

How cookies work

Before introducing what cookies are, let’s look at how cookies work:

1. First of all, we assume that there is no cookie under the current domain name
2. Next, the browser sends a request to the server (the request has not been brought with a cookie)
3. The server sets cookies and sends them to the browser (or not)
4. The browser saves the cookie
5. Next, every subsequent request will bring these cookies and send them to the server

Verification

Let’s verify

//Modify main.js

app.get('/', (req, res) => {
  //The server receives the request and sets a cookie for the response
  //The name of this cookie is testname
  //Value is testvalue
  res.cookie('testName', 'testValue')
  res.send('<h1>hello world!</h1>')
})

//After saving, restart the server
// node main.js

Open nowhttp://localhost:3000

  1. We seeRequest HeadersThere is no cookie field
  2. howeverResponse HeadersYes.Set-CookieThis field

The practice of cookie in front end

Now let’s refresh the page, which is equivalent to redirectinghttp://localhost:3000/This address made a request.

The practice of cookie in front end

Now we can see that the cookie field has been brought. Refresh it several times to see if the cookie is still there.

document.cookie

JS provides a way to get cookies:document.cookie, let’s set up more cookies first.

app.get('/', (req, res) => {
  res.cookie('testName0', 'testValue0')
  res.cookie('testName1', 'testValue1')
  res.cookie('testName2', 'testValue2')
  res.cookie('testName3', 'testValue3')
  res.send('<h1>hello world!</h1>')
})

The practice of cookie in front end

As we can see, a cookie is a string. But this string is formatted by a key value pairkey=valueThe key value pairs are composed ofA semicolonandA blank spaceSeparate.

What is cookie

After all that, you should know what a cookie is. Here are the following points:

  • A cookie is a small piece of text stored on a user’s computer by a browser
  • Cookies are plain text and do not contain any executable code
  • Cookies consist of key value pairs separated by semicolons and spaces
  • Although cookies are stored in the browser, they are usually set by the server
  • The size of cookies is limited to about 4KB

Properties options for cookies

Each cookie has certain attributes, such as when it is invalid, which domain name to send to, which path, and so on. When setting any cookie, you can set the relevant properties, or you can leave them unset. The default values of these properties will be used.

expires / max-age

expires / max-ageControl cookiesFailure timeOptions. If these two options are not set, the default valid period is session, that is, session cookie. This kind of cookie is gone when the browser is closed.

expires

expiresOption is used to set when the cookie is valid,expiresIt’s actually the cookie expiration date.
expiresMust be a time in GMT format (can be accessed throughnew Date().toGMTString()perhapsnew Date().toUTCString()To get)

app.get('/', (req, res) => {
  //This cookie will expire in ten seconds
  res.cookie('testName0', 'testValue0', {
    expires: new Date(Date.now() + 10000)
  })
  //This cookie does not set expiration time
  res.cookie('testName1', 'testValue1')
  res.send('<h1>hello world!</h1>')
})

Two cookies are set in the above code server, one is set with the expiration time, the other is not set, that is, the default expiration time session. Now let’s restart the service and refresh the page.

The practice of cookie in front end

Now the response header has been added with the response’s set failure time field. Enter the following code in the console.

Console. Log (` the current cookie is ${document. Cookie} '))
setTimeout(() => {
  Console. Log (` cookie after 5 seconds is ${document. Cookie} '))
}, 5000)
setTimeout(() => {
  Console. Log (` the cookie after 10 seconds is ${document. Cookie} '))
}, 10000)

The practice of cookie in front end

Therefore, after the expiration time of the cookie, the cookie can not be accessed through document.cookie. Of course, the invalid cookie will not be brought to the sending request in the future.

max-age

expiresIs an option in the HTTP / 1.0 protocol, in the new http / 1.1 protocolexpiresAlready bymax-ageOption instead, both limit the effective time of cookies.expiresThe value of is a point in time(Cookie expiration time = expires) andmax-ageThe value of is asecondIs the unit time period(Cookie expiration time = creation time + Max age)

//Set Max age, which is calculated from the moment the cookie is created
//How many seconds before the cookie expires
app.get('/', (req, res) => {
  res.cookie('testName0', 'testValue0', {
    //The parameter express is in milliseconds
    //The actual sending to the browser will be converted to seconds
    //Failure in ten seconds
    maxAge: 10000
  })
  res.cookie('testName1', 'testValue1')
  res.send('<h1>hello world!</h1>')
})

The practice of cookie in front end

priority

If Max age and expires are set at the same time, the time of Max age shall prevail.

app.get('/', (req, res) => {
  res.cookie('name0', 'value0')
  res.cookie('name1', 'value1', {
    expires: new Date(Date.now() + 30 * 1000),
    maxAge: 60 * 1000
  })
  res.cookie('name2', 'value2', {
    maxAge: 60 * 1000
  })
  res.send('<h1>hello world!</h1>')
})

The practice of cookie in front end

Domain and path

namedomainandpathA unique cookie can be identified.domainandpathThe two options together determine when cookies are automatically added to the request header by the browser. Please refer to the scope and path of cookies for details.

If these two options are not set, the default values are used.domainThe default value of is the domain name of the web page where the cookie is set,pathThe default value is the directory of the web page where the cookie is set.

secure

The secure option is used to set cookies to be sent only in secure requests. When the request is HTTPS or other security protocol, the cookie containing the secure option can be saved to the browser or sent to the server.

By default, cookies do not have the secure option (that is, empty). So by default, no matter the request of HTTPS protocol or HTTP protocol, the cookie will be sent to the server.

httpOnly

This option is used to set whether cookies can be accessed through JS. By default, cookies do not carryhttpOnlyOption (that is, null). The client can access the cookie (including reading, modifying, deleting, etc.) through JS code. When a cookie comes withhttpOnlyOption, the client can not access the cookie (including reading, modifying, deleting, etc.) through JS code.

Take a look at the code, modify main.js, save and restart the service, and refresh the page.

app.get('/', (req, res) => {
  res.cookie('notHttpOnly', 'testValue')
  res.cookie('httpOnlyTest', 'testValue', {
    httpOnly: true
  })
  res.send('<h1>hello world!</h1>')
})

The practice of cookie in front end

Look at the picture. It’s sethttpOnlyThere is an extra tick for the cookie. And passdocument.cookieUnable to access that cookie.

The practice of cookie in front end

On the client side, you cannot set ahttpOnlyType of cookie. This type of cookie can only be set by the server. When sending a request, we see that the request header still carries this settinghttpOnlyAs shown in the following figure.

The practice of cookie in front end

Set cookies

Make it clear: cookies can be set by the server or the client. I believe you can understand it here.

Server set cookies

Looking back at the picture just now, we set up many cookies.

The practice of cookie in front end

  • A set cookie field can only set one cookie. When you want to set multiple cookies, you need to add the same set cookie field
  • The server can set all options of cookies: expires, domain, path, secure, httponly

Client settings cookie

We can also set cookies through JS code in web page or client.

Set up

document.cookie = 'name=value'

You can set the following options for cookies: expires, domain, path, and use the;andBlank spaceSeparate

document.cookie='name=value; expires=Thu, 26 Feb 2116 11:50:25 GMT; domain=sankuai.com; path=/';

secure

Only in the webpage of HTTPS protocol can the client set the cookie of secure type successfully

HttpOnly

Cannot set httponly option in client

Delete cookie

The name, path, and domain of a cookie uniquely identify a cookie. We can delete a cookie by setting its max age to 0.

let removeCookie = (name, path, domain) => {
  document.cookie = `${name}=; path=${path}; domain=${domain}; max-age=0`
}

Scope and scope path of cookie

Scope of action

Before we talk about this scope, let’s make a simple understanding of domain names.

Child domain, relative to the parent domain, refers to every segment in the domain name. The subdomains are separated by decimal points. The subdomain at the end of the domain name is called the highest level subdomain, or primary domain, and the subdomain in front of it is called the secondary domain.

Here is an example,news.163.comandsports.163.comIt’s a subdomain.163.comIs the parent domain.

The practice of cookie in front end

When the domain of the cookie isnews.163.com, then visitnews.163.comI will bring cookies with me;
When the domain of the cookie is163.com, then visitnews.163.comandsports.163.com They’ll bring cookies

Path of action

When the domain of a cookie is the same, there are rules for whether to bring a cookie.

The practice of cookie in front end

Cookies that access the parent path can be accessed within the child path, which in turn cannot.

Let’s take a look at the example, or modify it firstmain.js

app.get('/parent', (req, res) => {
  res.cookie('parent-name', 'parent-value', {
    path: '/parent'
  })
  Res.send ('< H1 > parent path! < H1 >')
})

app.get('/parent/childA', (req, res) => {
  res.cookie('child-name-A', 'child-value-A', {
    path: '/parent/childA'
  })
  Res.send ('< H1 > subpath a! < H1 >')
})

app.get('/parent/childB', (req, res) => {
  res.cookie('child-name-B', 'child-value-B', {
    path: '/parent/childB'
  })
  Res.send ('< H1 > subpath B! < H1 >')
})

The “domain” here should be changed to the path

The practice of cookie in front end
The practice of cookie in front end
The practice of cookie in front end

Reference articles

  • Let’s talk about cookies
  • Scope of cookies
  • Use of cookies and sessions