session

72 阅读1分钟

引言: cookie:

  • 存在客户端
  • 优点
    • 存储在客户端,不占用服务器资源
  • 缺点
    • 只能是字符串格式
    • 存储量有限
      • sessionStorage
      • localStorage
    • 数据容易被获取
    • 数据容易被篡改
    • 容易丢失

session

  • 存储在服务器端
  • 优点
    • 可以是任何格式
    • 存储量理论上是无限的
    • 数据难以被获取
    • 数据难以篡改
    • 不易丢失
  • 缺点
    • 占用服务器资源(提高成本)

session原理图

image.png

使用

init.js

const session = require("express-session");
app.use(session({
    secret:"yuanjin",
    name:"sessionid",
}));

index.js

login.onclick = function () {
    fetch("/api/admin/login", {
        method: "post",
        headers: {
            "content-type": "application/json",
        },
        body: JSON.stringify({
            loginId: "abc",
            loginPwd: "123123",
        }),
    })
    .then((resp) => resp.json())
    .then((resp) => {
        console.log(resp);
    });
};

admin.js

router.post(
  "/login",
  asynchandler(async (req, res) => {
    const result = await adminServ.login(req.body.loginId, req.body.loginPwd);
    if (result) {
    let value = result.id;
    value = crypto.encrypt(value.toString());
    //登录成功
    req.session.loginUser = result;
    }
    return result;
}

module.exports = router;

tokenMiddleware.js

module.exports = (req, res, next) => {
    // /api/student/:id 和 /api/student/1771
    const apis = needTokenApi.filter((api) => {
        const reg = pathToRegexp(api.path);
        return api.method === req.method && reg.test(req.path);
    });
    if (apis.length === 0) {
        next();
        return;
    }

    if (req.session.loginUser) {
        //说明已经登录过了
        next();
    } else {
        handLeNonToken(req, res, next);
    }
};

//处理没有认证的情况
function handLeNonToken(req, res, next) {
    res
    .status(403)
    .send(getErr("you don't have any token to access the api", 403));
}