“This is the second day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

If the heart yearns for what fear road resistance and long

Continuously updated…

Portal series:

  • Egg Introduction Basics Egg introduction to project creation
  • Egg Project Directory and controller
  • Egg Basic Egg unit tests
  • Egg Basic HTTP request
  • Egg Basic knowledge Egg Service Service
  • Egg Template rendering
  • Egg Basic knowledge Egg Cookie operation

To understandCookeie

Above, we learned Egg template rendering engine -EJS. In this article, we mainly introduce the operation of Cookie.

First of all, we need to understand what a Cookie is. A Cookie is actually a small piece of text (key-value format). The client makes a request to the server, and if the server needs to record the user status, it issues a Cookie to the client browser using Response. The client browser saves the Cookie.

So what does a Cookie do? When the browser requests the site again, the browser submits the requested URL along with the Cookie to the server. The server checks the Cookie to identify the user’s state.

HTTP requests are stateless, but our Web applications often need to know who is making the request. To solve this problem, the HTTP protocol designs a special request header: Cookie. The server can respond to a small amount of data to the client through the response header (set-cookie), and the browser will follow the protocol to save the data and bring it with it when requesting the same service next time (the browser will also follow the protocol and only bring the corresponding cookie when visiting websites that comply with the cookie specified rules to ensure security).

Now that we know about cookies, let’s do cookies in our code

Create a template

The basic operation of Cookie is divided into add, delete, change and check (in the actual development of Cookie erasing total should be in the server side, rather than in the client’s operation).

We create cookie. HTML template file under app/ View, and create four buttons in it, namely, add cookie, delete cookie, modify cookie and view cookie, and bind corresponding events for each button. We call the method of fetch to add, delete, change and check the Cookie in the event, and the code is as follows

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Cookie operation</title>
</head>
<body>
  <div>
    <button onclick="add()">Increase the Cookie</button>
    <button onclick="delelte()">Delete the Cookie</button>
    <button onclick="update()">Modify the Cookie</button>
    <button onclick="search()">Query the Cookie</button>
  </div>
  <script>
    function add() {
      fetch('/addcookie', {
        method: 'post'.headers: {
          "Content-type": "application/json"}}); }function delelte() {
      fetch('/deletecookie', {
        method: 'post'.headers: {
          "Content-type": "application/json"}}); }function update() {
      fetch('/updatecookie', {
        method: 'post'.headers: {
          "Content-type": "application/json"}}); }function search() {
      fetch('/searchcookie', {
        method: 'post'.headers: {
          "Content-type": "application/json"}}); }</script>
</body>
</html>
Copy the code

Obviously, we don’t have such methods to call first, so let’s write these methods

The controller

Create cookie.js file under app/controller. In the cookie.js file, first write a cookie method to render the cookie. HTML template we just created, and then write the code of add, delete, change and check method used in the template as follows

'use strict';

const Controller = require('egg').Controller;

class CookieController extends Controller {
  async cookie() {
    const { ctx } = this;
    await ctx.render('cookie')}async add() {
    const { ctx } = this;
    ctx.cookies.set('user'.'vience')
    ctx.body = {
      code: 200.message: 'Cookie added successfully'}}async del() {
    const { ctx } = this;
    ctx.cookies.set('user'.null)
    ctx.body = {
      code: 200.message: 'Cookie deleted successfully'}}async update() {
    const { ctx } = this;
    ctx.cookies.set('user'.'tangxd3')
    ctx.body = {
      code: 200.message: 'Cookie modified successfully'}}async search() {
    const { ctx } = this;
    const user = ctx.cookies.get('user') | |' '
    console.log('user: ', user);
    ctx.body = {
      code: 200.message: 'Cookie query successful'.data: user
    }
  }
}

module.exports = CookieController;
Copy the code

After the controller code is complete, we configure the route in /app/router.js

/ / cookie
router.get('/cookie', controller.cookie.cookie);
router.post('/addcookie', controller.cookie.add);
router.post('/deletecookie', controller.cookie.del);
router.post('/updatecookie', controller.cookie.update);
router.post('/searchcookie', controller.cookie.search);
Copy the code

The effect

We can look at cookies in the Application in the console,

grammar

ctx.cookies.set(key, value, options)

increase

ctx.cookies.set('user', 'vinece')

delete

ctx.cookies.set('user', null)

Modify the

ctx.cookies.set('user', 'tangxd3')

The query

ctx.cookies.get('user')

configuration

The third parameter of ctx.cookie. set(key, value, options) is the configuration item, which can carry out some configuration options, such as valid time, server operation Settings and Chinese encryption.

Valid Event (60s)

maxAge: 1000 * 60

Server operation Settings

Whether only the server is allowed to change,

When the value is false, the value of the cookie can be printed from the console via document.cookie

When true, an empty string of cookies is printed on the console via document.cookie

httpOnly: true

Chinese encryption (If the cookie value is Chinese, you can use encrypt to store the cookie, or you can use Base64. This is difficult.)

encrypt: true

Use in increment and query methods

// Add methods
async add() {
  const { ctx } = this;
  ctx.cookies.set('user'.'vinece', {
    // Valid time
    maxAge: 1000 * 60.// Whether to allow server modification only,
    // When the value is false, the value of the cookie can be printed on the console via document.cookie
    // When true, the console prints the cookie with an empty string through document.cookie
    httpOnly: true.// Whether to encrypt the cookie (if the cookie value is Chinese, you can use encrypt to store the cookie, or you can use Base64, which is more difficult)
    encrypt: true
  })
  ctx.body = {
    code: 200.message: 'Cookie added successfully'}}Copy the code
// Change the method
async search() {
  const { ctx } = this;
  const user = ctx.cookies.get('user', {
    // Decrypt with encrypt set to true
    encrypt: true}) | |' '
  console.log('user: ', user);
  ctx.body = {
    code: 200.message: 'Cookie query successful'.data: user
  }
}
Copy the code

Write in the last

Follow me, more content continues to output

🌹 if you like, give it a thumbs up 👍🌹

🌹 feel harvest, can come to a wave of collection + attention, so as not to find you next time I 😁🌹

🌹 welcome everyone to leave a message exchange, criticism and correction, forwarding please indicate the source, thank you for your support! 🌹