node.js cookie
时间: 2023-09-27 12:12:13 浏览: 110
A cookie is a small piece of data that is stored on the client's computer by the server. In Node.js, cookies can be created and read using the built-in `http` module.
To set a cookie in Node.js, you can use the `setHeader()` method on the response object with the `Set-Cookie` header. Here's an example:
```
const http = require('http');
http.createServer((req, res) => {
res.setHeader('Set-Cookie', 'username=john');
res.end('Cookie set');
}).listen(3000);
```
In this example, we're setting a cookie named `username` with the value `john`.
To read a cookie in Node.js, you can use the `cookie-parser` middleware. Here's an example:
```
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
app.get('/', (req, res) => {
const username = req.cookies.username;
res.send(`Hello ${username}`);
});
app.listen(3000);
```
In this example, we're using the `cookie-parser` middleware to parse the `Set-Cookie` header and store it in `req.cookies`. We can then access the `username` cookie using `req.cookies.username`.
阅读全文