1. 什么是cookie
In Node.js, you can use the response.setHeader
method to set cookies from the server side. Here’s an example using the Express.js framework:
1 | const express = require('express'); |
In this example, res.cookie('username', 'John Doe', { maxAge: 900000, httpOnly: true });
sets a cookie named “username” with the value “John Doe”. The maxAge
option sets the expiry time for the cookie in milliseconds. The httpOnly
option is a security enhancement that restricts the cookie from being accessed by client-side scripts.
Get cookie by request header
In Node.js, you can use the request.headers.cookie
property to get cookies from the client side. Here’s an example using the Express.js framework:
1 | const express = require('express'); |
In this example, const cookie = req.headers.cookie;
gets the cookie from the client side and logs it to the console.
You can also use cookie-parser
middleware to parse the cookie from the request header. Here’s an example using the cookie-parser
middleware:
1 | const express = require('express'); |
使用JavaScript操作cookie
Create cookie
Note that the cookie value cannot contain semicolons, commas, or whitespace. For a solution, use the encodeURIComponent() function to encode the value.
1 | document.cookie = "username=John Doe; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/"; |
document.cookie will return all cookies in one string, each cookie is separated by a semicolon and a space.
Read a cookie
1 | let allCookies = document.cookie; |
Delete a cookie
To delete a cookie, just set the expires parameter to a passed date.
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
# References
- [MDN web docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies)