The basic use

Create a cookie

The res.cookie() method is used to add set-cookie to the response header.

 function(req, res, next){... res.cookie(name, value [, options]); . }Copy the code

The res.cookie() method takes three arguments:

  • name: Indicates the key of the cookieString
  • value: the type ofStringorObject
  • option: Is of type object and can use the following attributes:
The property name type instructions
domain String Cookie valid domain name
expires Date Cookie expiration time
httpOnly Boolean Cookies run only through Http access
maxAge Number How many milliseconds after the cookie expires
path String Cookie valid path
secure Boolean Cookies only run over HTTPS
signed Boolean Whether to use a signature requires coordinationcookie-parseruse

Using cookies

To use cookies in Express, we need to use cookie-Parser

The installationcookie-parser

Install the cookie-parser package using NPM

$ npm install cookie-parser
Copy the code

Configuring middleware

Call app.use() to configure cookie-parser’s middleware

const express = require("express");
const app = express();
const cookieParser = require("cookie-parser");

app.use(cookieParser());
Copy the code

To get a cookie

After the above steps are complete, we can use req.cookies to get parsed cookies, which are parsed as objects by cookie-parser.

app.get("/".async function (req, res) {
  res.send(req.cookies)
});
Copy the code

Remove the cookie

In express.js, there are two ways to make cookies clear:

res.clearCookie()

The first is to use the res.clearcookie () method provided by Express.js for.

res.clearCookie(name [, options]);
Copy the code

maxAge: -1

The second option is to set maxAge: -1 to expire immediately:

res.cookie(name, value, { maxAge: -1 });
Copy the code

In actual combat

Here we use express.js to complete the three interfaces, respectively:

  • User Login Or not
  • The user login
  • The user to log out

Importing dependency packages

First we introduce Express dependencies, configure the middleware, and listen for the corresponding ports.

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const port = 3099;
const cookieParser = require("cookie-parser");

app.use(bodyParser.json());
app.use(cookieParser());

app.listen(port, () = > {
  console.log(`node listening at http://localhost:${port}`);
});

Copy the code

Checking login

// Check whether the user is logged in
app.get("/".async function (req, res) {
  if (req.cookies.USER_ID) {
    res.send({
      success: true.info: 【 ` users${req.cookies.USER_ID}】 Logged in to '.cookie: req.cookies.USER_ID,
    });
  } else {
    res.send({
      success: false.info: "User not logged in"}); }});Copy the code

The user login

// User login
app.post("/login".async function (req, res) {
  const { name, pwd } = req.body;
  if (name === "abc" && pwd === 123) { // The name and PWD should be retrieved from the database
    res.cookie("USER_ID"."abc", {
      domain: ".node.com".// Set the valid domain name
      httpOnly: true.// Only Http access is run
      maxAge: 1000 * 60 * 60 * 2.// 2 hours to expire
    });
    res.send({
      success: true.info: "Login successful"}); }else {
    res.send({
      success: false.info: "Login failed"}); }});Copy the code

The user to log out

// The user logs out
app.get("/logout".async function (req, res) {
  res.cookie("USER_ID"."abc", {
    domain: ".node.com".httpOnly: true.maxAge: -1./ / overdue
    httpOnly: true}); res.send({success: true.info: "Logout successful"}); });Copy the code

Change the value to signed cookie

When we access the cookie of the browser after successful login, we can see that the value of the cookie is displayed in clear text, which is actually very insecure, and users may tamper with the cookie.

Set up thesigned

So we need to sign the cookie to prevent user tampering. The res.cookie() method provides a signed configuration that, if set to true, will sign it. Let’s modify the /login route

app.post("/login".async function (req, res) {
  const { name, pwd } = req.body;
  if (name === "abc" && pwd === 123) {
    res.cookie("USER_ID"."abc", {
      domain: ".node.com".httpOnly: true.maxAge: 1000 * 60 * 60 * 2.signed: true.// Set the signature
    });
    res.send({
      success: true.info: "Login successful"}); }else {
    res.send({
      success: false.info: "Login failed"}); }});Copy the code

String to add a signature

When you specify signed:true without completing the signature process, we need to add the signature string to the cookieParser(Secret) method to implement the signature. Modify cookie-parser middleware calls:

app.use(cookieParser("your_sercret_str"));
Copy the code

usesignedCookies

Before we set signed:true, we used req.cookies to get cookies, but once signed, we need to use req.signedCookies to get signatures so we can modify/route.

app.get("/".async function (req, res) {
  if (req.signedCookies.USER_ID) {
    res.send({
      success: true.info: 【 ` users${req.signedCookies.USER_ID}】 Logged in to '.cookie: req.cookies.USER_ID,
      signedCookies: req.signedCookies.USER_ID,
    });
  } else {
    res.send({
      success: false.info: "User not logged in"}); }});Copy the code