Home  >  Article  >  Web Front-end  >  The mystery of cookie storage revealed: a detailed explanation of the interaction between the browser and the server

The mystery of cookie storage revealed: a detailed explanation of the interaction between the browser and the server

WBOY
WBOYOriginal
2024-01-19 09:19:041007browse

The mystery of cookie storage revealed: a detailed explanation of the interaction between the browser and the server

With the development of the Internet, we increasingly use browsers for web browsing, shopping, logging in and other operations. In these processes, we often hear a word - cookie. So what exactly are cookies? What is its function? Today we will reveal the mystery of cookie storage, analyze the interaction between the browser and the server in detail, and give specific code examples.

1. What are cookies?

Simply put, a cookie is a small piece of data sent by the server to the browser and stored locally. Each time the browser makes a request to the same server, it will bring the previously saved cookie data. In this case, the server can read the cookie data in the browser and perform corresponding operations based on the information in it.

2. The role of cookies

  1. Session state management

Through cookies, the server can identify the user and keep it when the user visits the website again. The user's session state. For example, when we log in, the server will send a cookie containing our login information to the browser, so that when we visit the website again, the server can recognize us like the last time and log in automatically.

  1. Personalized Settings

Through cookies, the server can obtain some of the user's personal habits and preferences and other information, thereby providing users with more personalized services and suggestions. . For example, when we browse a shopping website, the server will recommend related products based on our previous purchase records and browsing history.

  1. Tracking Analysis

Through cookies, the server can track the user's browsing habits to perform relevant analysis and statistics. For example, an advertising company can use cookies to track information such as the time and frequency of users' visits to different websites, so as to understand users' interests and purchasing desires and provide advertisers with better advertising promotion services.

3. Interaction between the browser and the server

The saving and acquisition of cookies are carried out between the browser and the server. The entire interaction process can be divided into the following four steps:

  1. The browser sends a request to the server, and the request does not contain cookie information.
  2. After the server receives the request, it generates and sends cookie data to the browser.
  3. After the browser receives the cookie data, it saves it locally.
  4. The browser sends a request to the same server again, carrying the previously saved cookie data in the request.

To better understand this process, let’s look at a specific example.

(1) Server code example

The following is a server code written using the Node.js framework to send a response containing cookie information to the browser.

const http = require('http');

http.createServer((req, res) => {
  //设置cookie
  res.writeHead(200, {
    'Set-Cookie': 'name=cookie_test; max-age=60'
  });

  //发送响应
  res.end('Hello World!
');
}).listen(8080);

console.log('Server running at http://localhost:8080/');

Code analysis:

  • Use the Set-Cookie field in the server response header to send cookie data to the browser.
  • Set the validity period of the cookie through the max-age parameter, here it is set to 60 seconds.

(2) Browser code example

The following is a browser code written in JavaScript to send a request to the above server and output cookie information when the response is received .

// 发送请求
fetch('http://localhost:8080')
  .then(response => {
    // 读取cookie
    console.log(response.headers.get('Set-Cookie'));
    return response.text();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => console.error(error));

Code analysis:

  • Use the fetch function to send a request to the server.
  • Read the cookie information in the response header through the response.headers.get('Set-Cookie') method.
  • Use the response.text() method to obtain the text information in the response body.

4. Common attributes of cookies

In addition to the max-age attribute used in the above example, cookies have many other attributes. Common attributes are as follows:

  1. Path

This attribute specifies the path of the cookie. When the browser initiates a request, the cookie will be brought only if the request path exactly matches the cookie path.

res.writeHead(200, {
  'Set-Cookie': 'name=value; Path=/test'
});
  1. Domain

This attribute specifies the domain name of the cookie. When the browser initiates a request, the cookie will be included only if the requested domain name exactly matches the domain name of the cookie.

res.writeHead(200, {
  'Set-Cookie': 'name=value; Domain=.example.com'
});
  1. Expires

This attribute specifies the validity period of the cookie. After this attribute is set, the cookie will automatically expire at the specified time and be deleted by the browser.

res.writeHead(200, {
  'Set-Cookie': 'name=value; Expires=Wed, 18 Nov 2020 08:51:29 GMT'
});
  1. Secure

This attribute specifies whether the cookie can only be sent through the https protocol. After setting this attribute, the cookie will only be brought when an https request is made.

res.writeHead(200, {
  'Set-Cookie': 'name=value; Secure'
});
  1. HttpOnly

This attribute specifies whether the cookie can only be sent through the http protocol. After setting this attribute, the browser cannot obtain the cookie information through JavaScript, thereby improving cookie security.

res.writeHead(200, {
  'Set-Cookie': 'name=value; HttpOnly'
});

5. Summary

Through the introduction of this article, we have learned about the definition, function, storage method and common attributes of cookies. At the same time, we also learned the cookie interaction model between the browser and the server, and deepened our understanding of cookies through specific code examples. As a front-end engineer, we should have an in-depth understanding and mastery of cookie-related knowledge in order to apply it more flexibly and efficiently in actual development.

The above is the detailed content of The mystery of cookie storage revealed: a detailed explanation of the interaction between the browser and the server. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn