0%

javascript-cookie

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
2
3
4
5
6
7
8
9
10
11
const express = require('express');
const app = express();

app.get('/', (req, res) => {
res.cookie('username', 'John Doe', { maxAge: 900000, httpOnly: true });
res.end('Cookie has been set');
});

app.listen(3000, () => {
console.log('Server is running on port 3000');
});

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.

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
2
3
4
5
6
7
8
const express = require('express');
const app = express();

app.get('/', (req, res) => {
const cookie = req.headers.cookie;
console.log(cookie);
res.end('Cookie has been set');
});

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
2
3
4
5
6
7
8
9
10
const express = require('express');
const cookieParser = require('cookie-parser');

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

app.get('/', (req, res) => {
const { cookies } = req;
console.log(cookies);
});

使用JavaScript操作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.

1
let allCookies = document.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)