使用Cookie

Express框架本体没有对Cookie进行支持,但我们可以安装cookie-parser库实现读取和写入Cookie。

安装cookie-parser

执行以下命令安装cookie-parser

npm i cookie-parser

cookie-parser库以中间件的形式集成到Express中,因此我们需要使用app.use()添加中间件,具体写法可以参考下面的例子。

读取和写入Cookie

下面例子中,我们演示如何向Cookie中读取和写入数据。

import express from "express";
import cookieParser from "cookie-parser";

const app = express();
const router = express.Router();

router.get("/", (req, res, next) => {
  // 读取Cookie
  const token = req.cookies.token;
  console.log(token);
  // 写入Cookie
  res.cookie("token", { username: "root", token: "abc123def456" });
  res.sendStatus(200);
});

app.use(cookieParser());
app.use(router);
app.listen(8080, () => {
  console.log("Express server listen on 8080");
});

读取Cookie很简单,我们直接读取req.cookies就行了,写入Cookie调用res.cookie()即可。

Cookie配置选项

res.cookie()方法支持第三个参数用于配置Cookie的各项属性。

res.cookie("token", "abc123", {
  maxAge: 1000 * 60 * 60 * 24, // 过期时间,单位毫秒
  httpOnly: true,              // 仅HTTP访问,禁止JavaScript读取
  secure: true,                // 仅在HTTPS下传输
  sameSite: "strict",          // 跨站策略:strict / lax / none
  path: "/",                   // Cookie生效路径
  domain: "example.com",       // Cookie生效域名
});

常用配置项说明如下表。

配置项 说明
maxAge Cookie有效期,单位为毫秒,不设置则为会话Cookie(浏览器关闭后失效)
httpOnly 设置为true时,Cookie无法被客户端JavaScript访问,可防止XSS攻击
secure 设置为true时,Cookie仅在HTTPS连接下传输
sameSite 控制跨站请求时是否发送Cookie,可选值为strictlaxnone
path Cookie生效的路径,默认为/
domain Cookie生效的域名

清除Cookie

清除Cookie可以使用res.clearCookie()方法。

router.get("/logout", (req, res, next) => {
  res.clearCookie("token");
  res.sendStatus(200);
});

注意:清除Cookie时,如果写入时指定了pathdomain等选项,清除时也需要指定相同的选项才能正确清除。

res.clearCookie("token", { path: "/", domain: "example.com" });

签名Cookie

cookie-parser支持对Cookie进行签名,防止客户端篡改Cookie值。使用签名Cookie需要在初始化中间件时传入密钥。

import express from "express";
import cookieParser from "cookie-parser";

const app = express();
const router = express.Router();

// 初始化时传入签名密钥
app.use(cookieParser("my-secret-key"));

router.get("/", (req, res, next) => {
  // 读取签名Cookie
  const token = req.signedCookies.token;
  console.log(token);
  // 写入签名Cookie
  res.cookie("token", "abc123", { signed: true });
  res.sendStatus(200);
});

app.use(router);
app.listen(8080, () => {
  console.log("Express server listen on 8080");
});

签名Cookie的读取需要通过req.signedCookies而不是req.cookies。如果Cookie被篡改,req.signedCookies中对应的值将为false

作者:Gacfox
版权声明:本网站为非盈利性质,文章如非特殊说明均为原创,版权遵循知识共享协议CC BY-NC-ND 4.0进行授权,转载必须署名,禁止用于商业目的或演绎修改后转载。