Table of Contents
Why do we need cookies
What is a cookie
Regular cookie
Signed cookie
Summary
Home Web Front-end JS Tutorial What are cookies in node? how to use?

What are cookies in node? how to use?

Sep 13, 2018 pm 04:25 PM
cookie express javascript node.js

The content of this article is about what are cookies in node? how to use? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Why do we need cookies

We know that http is a stateless protocol. What does stateless mean?
Let me give a small example to illustrate: For example, Xiao Ming is shopping online. He browses multiple pages and purchases some items. These requests are completed in multiple connections. If no additional means are used, the server cannot We know exactly what he purchased, because the server simply doesn’t know whether the person requesting each time is Xiao Ming, unless Xiao Ming has a identification to prove that he is Xiao Ming.

So, in order to identify the user's identity and perform session tracking, cookies appear.

Simply put, a cookie is an identifier.
Strictly speaking, a cookie is some information stored on the client. It is submitted by the browser to the server every time it is connected, and the server also initiates a request to the browser to store the cookie, relying on this method. , the server can identify the client.
Specifically, when the browser initiates a request to the server for the first time, the server will generate a unique identifier and send it to the client browser. The browser will store this unique identifier in Cookie. In each request initiated, the client browser transmits this unique identifier to the server, and the server uses this unique identifier to identify the user.

Having said so much, open the browser and let’s take a look at this product first.

What are cookies in node? how to use?

In the picture above, it is a cookie stored in the browser. Its name is name and its value is abc.

It’s not enough to just look at it. Next, let’s use node to make a regular cookie.
First, install the express framework and cookieParser middleware

npm i express --save
npm install cookie-parser --save
Copy after login

The main uses of cookieParser middleware are as follows:

  1. Parse cookies from the browser and put them in req. In cookies;

  2. For signed cookies, sign and unsign cookies

The code is as follows:

var express = require('express');
var cookieParser = require('cookie-parser');

var app = express();
app.use(cookieParser());

app.use(function (req, res) {
  if (req.url === '/favicon.ico') {
    return
  }

  // 设置常规cookie, 有效期为20s, 客户端脚本不能访问它的值
  res.cookie('name', 'abc', { signed: false, maxAge: 20 * 1000, httpOnly: true });
  console.log(req.cookies, req.url, req.signedCookies);

  res.end('hello cookie');
})

app.listen(4000)
Copy after login

After running, Open http://localhost:4000/
in the browser. Taking chrome as an example, open the browser debugging tool with f12, and you can find the cookie you defined among the cookies in the application.
The req.cookies and req.signedCookies attributes are the parsing results of the cookies in the request header sent with the http request.
Among them, req.cookies corresponds to ordinary cookies, and req.signedCookies corresponds to signed cookies.
If there is no cookie in the request, both objects will be empty.

Signed cookie is more suitable for sensitive data, because it can verify the integrity of the cookie data and help prevent man-in-the-middle attacks.
Valid signed cookies are placed in the req.signedCookies object.

The code is as follows:

var express = require('express');
var cookieParser = require('cookie-parser');

var app = express();

// 设置密钥,用来对cookie签名和解签, Express可以由此确定cookie的内容是否被篡改过
app.use(cookieParser('a cool secret'));

app.use(function (req, res) {
  if (req.url === '/favicon.ico') {
    return
  }

  // 设置签名cookie, 并且有效期为1min
  res.cookie('name', 'efg', { signed: true, maxAge: 60 * 1000, httpOnly: true });
  console.log(req.cookies, req.url, req.signedCookies);

  res.end('signed cookie');
})
app.listen(4000)
Copy after login

After running, open http://localhost:4000/
Take chrome as an example, f12 to open the browser debugging tool, in the application You can find the signed cookie you defined in the cookies, the format is as follows: s:efg.7FJDuO2E9LMyby6+o1fGQ3wkIHGB9v1CDVWod8NQVAo
. The left side of the number is the value of the cookie, and the right side is the encrypted hash value generated by SHA-1 HMAC on the server.
If the value of this signed cookie is tampered with, the decryption of the cookie on the server will fail, and the req.signedCookies output in the node will be false. As follows:

What are cookies in node? how to use?

And if the cookie is passed intact, it will be parsed correctly:

What are cookies in node? how to use?

Summary

You can store any type of text data in a cookie, but usually a session cookie is stored on the client side so that you can Preserve full user state on the server side.

Related recommendations:

Detailed explanation of Promise in jQuery, Angular, and node

##How to use the cluster cluster in node

The above is the detailed content of What are cookies in node? how to use?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Where are the cookies on your computer? Where are the cookies on your computer? Dec 22, 2023 pm 03:46 PM

Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

Where are cookies stored? Where are cookies stored? Dec 20, 2023 pm 03:07 PM

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

Where are the mobile cookies? Where are the mobile cookies? Dec 22, 2023 pm 03:40 PM

Cookies on the mobile phone are stored in the browser application of the mobile device: 1. On iOS devices, Cookies are stored in Settings -> Safari -> Advanced -> Website Data of the Safari browser; 2. On Android devices, Cookies Stored in Settings -> Site settings -> Cookies of Chrome browser, etc.

Detailed explanation of where browser cookies are stored Detailed explanation of where browser cookies are stored Jan 19, 2024 am 09:15 AM

With the popularity of the Internet, we use browsers to surf the Internet have become a way of life. In the daily use of browsers, we often encounter situations where we need to enter account passwords, such as online shopping, social networking, emails, etc. This information needs to be recorded by the browser so that it does not need to be entered again the next time you visit. This is when cookies come in handy. What are cookies? Cookie refers to a small data file sent by the server to the user's browser and stored locally. It contains user behavior of some websites.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Comparative analysis of Express and Laravel: Choose the framework that suits you better Comparative analysis of Express and Laravel: Choose the framework that suits you better Mar 10, 2024 pm 10:15 PM

Express and Laravel are two very popular web frameworks, representing the excellent frameworks of the two major development languages ​​of JavaScript and PHP respectively. This article will conduct a comparative analysis of these two frameworks to help developers choose a framework that is more suitable for their project needs. 1. Framework Introduction Express is a web application framework based on the Node.js platform. It provides a series of powerful functions and tools that enable developers to quickly build high-performance web applications. Express

Frequently Asked Questions and Solutions about Cookie Settings Frequently Asked Questions and Solutions about Cookie Settings Jan 19, 2024 am 09:08 AM

Common problems and solutions for cookie settings, specific code examples are required. With the development of the Internet, cookies, as one of the most common conventional technologies, have been widely used in websites and applications. Cookie, simply put, is a data file stored on the user's computer that can be used to store the user's information on the website, including login name, shopping cart contents, website preferences, etc. Cookies are an essential tool for developers, but at the same time, cookie settings are often encountered

In-depth comparison of Express and Laravel: How to choose the best framework? In-depth comparison of Express and Laravel: How to choose the best framework? Mar 09, 2024 pm 01:33 PM

In-depth comparison of Express and Laravel: How to choose the best framework? When choosing a back-end framework suitable for your project, Express and Laravel are undoubtedly two popular choices among developers. Express is a lightweight framework based on Node.js, while Laravel is a popular framework based on PHP. This article will provide an in-depth comparison of the advantages and disadvantages of these two frameworks and provide specific code examples to help developers choose the framework that best suits their needs. Performance and scalabilityExpr

See all articles