Middleware for parsing cookies in HTTP requests
1. Installation
npm install cookie-parser
2. Basic use
const express = require("express"); const cookieParser = require("cookie-parser"); const app = express(); // Use cookie-parser middleware(cookieParser()); ("/", (req, res) => { // Get the cookies in the request const cookies = ; ("Cookies:", cookies); ("Cookie parsed successfully"); }); const port = 3000; (port, () => { (`Server running on port ${port}`); });
2. Analysis and setting Cookies
1. Analytics Cookies
`cookie-parser` will parse the requested cookies into an object and store them in ``. The value of the cookie can be obtained by accessing ``.
("/get-cookie", (req, res) => { const username = ; if (username) { (`Hello, ${username}`); } else { ("No username cookie found"); } });
2. Set cookies
Use the `()` method to set cookies in the response. This method accepts three parameters: the name, value of the cookie, and optional configuration object.
("/set-cookie", (req, res) => { // Set a cookie named username with a value of John, valid for 1 hour ("username", "John", { maxAge: 3600000, httpOnly: true }); ("Cookie set successfully"); });
3. Signature Cookies
`cookie-parser` supports signing of cookies to ensure the integrity and security of cookies. A signature cookie can be used when `cookie-parser` is initialized.
const express = require("express"); const cookieParser = require("cookie-parser"); const app = express(); // Use cookie-parser middleware with key(cookieParser("mysecretkey")); ("/set-signed-cookie", (req, res) => { // Set a signed cookie ("signedUsername", "Jane", { signed: true }); ("Signed cookie set successfully"); }); ("/get-signed-cookie", (req, res) => { // Get signature cookies const signedUsername = ; if (signedUsername) { (`Hello, ${signedUsername}`); } else { ("No signed username cookie found"); } }); const port = 3000; (port, () => { (`Server running on port ${port}`); });
3. Clear cookies
Use the `()` method to clear the client's cookies. You need to specify the name of the cookie to be cleared.
("/clear-cookie", (req, res) => { ("username"); ("Cookie cleared successfully"); });
This is the end of this article about the detailed explanation of Chinese cookie-parser dependencies. For more related cookie-parser dependencies, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!