loading

Express Cookie 不能保存在 Application 中

在前后端分离项目中,因为跨域策略,所以 Cookie 不能存储在浏览器的 Application 中。只能在请求的响应头处看到有 Set-Cookie:

1️⃣前端发送请求添加 withCredentials:

file:[webapp/src/api/api-user.js]
request.post("/login", {
  username, password
}, {
  withCredentials: true
}).then(({ data: res }) => {
  if ( res.data.length !== 0 && res.status == 200 ) {
    onSuccess(res.data, res.status);
  } else {
    onError ? onError(res) : "";
  }
}).catch(err => {
  onError ? onError(err) : "";
});

2️⃣Express 需要使用中间件cors解决跨域,添加 credentials、origin:

file:[serverapp/src/app.js]
import express from "express";
import cors from "cors";

const app = express();

app.use(cors({ credentials: true, origin: true }));

3️⃣发送 Cookie 的时候需要添加 domain,服务器生成的 Cookie 只能是相同或匹配的域才能使用,具体请看Cookie中的domain与path属性详解

file:[serverapp/src/api/api-user.js]
app.post("/login", (req, res) => {
  let user = queryUserByUnameAndPwd(req.body.uname, req.body.pwd);
  res.cookie("USERID", user.id, { domain: "localhost", maxAge: 60000 * 60 * 24 });
}

因为是本地开发,所以直接写的是 localhost。path 默认是/,指的是 localhost 下所有的路径都可以使用该 Cookie:

posted @ 2022-08-20 12:33  Himmelbleu  阅读(179)  评论(0编辑  收藏  举报