fastify session 抛出一些我不明白的东西

fastify session is throwing something that I dont understand

我对 fastify 会话有疑问。我正在使用打字稿:

import fastify from "fastify"
import randomString = require("crypto-random-string")
import fastifyCookie = require("fastify-cookie")
import fastifySession = require("fastify-session")

const app = fastify()

const safeSecret = randomString({length:32, type: 'base64'})

app.register(fastifyCookie)
app.register(fastifySession, {secret: safeSecret, saveUninitialized: true, cookie: {secure:false, httpOnly: true, sameSite: false, maxAge: 60 *60 *60}})

app.addHook('preHandler', (request, _reply, next) => {
    request.session.sessionData = {userId: String, name: String, email: String, password: String, loggedOn: Date};
    next();
})


app.get('/', (req, reply) => {
    let oldName = req.session.sessionData.name
    req.session.sessionData.name = randomString({length: 32, type: 'base64'})
    reply.send("name:" + req.session.sessionData.name + " old name: " + oldName)
})

app.get('/showmename', (req, reply) => {
    reply.send("name:" + req.session.sessionData.name)
})

app.listen(3000)

该代码有效,但是,当我首先访问 localhost/ 时,它显示我的随机名称,但旧名称是下面的代码。 showmename 和 oldname 说的完全一样。

name:function String() { [native code] }

我做错了什么吗?因为当我转到 localhost/showmename 时,firefox 的 cookie 编辑器插件向我显示了与 localhost/.

具有相同会话 ID 的完全相同的会话 cookie

preHandler 挂钩是 运行 每个请求,所以你每次都只是覆盖你的 sessionData:

app.addHook('preHandler', (request, _reply, next) => {
    request.session.sessionData = {userId: String, name: String, email: String, password: String, loggedOn: Date};
    next();
})

因此,nameString 构造函数,它被字符串化为您的输出。

您应该检查会话:

app.addHook('preHandler', (request, _reply, next) => {
  if (!request.session.sessionData) {
    request.session.sessionData = { userId: String, name: String, email: String, password: String, loggedOn: Date }
  }
  next()
})

那就可以了。

无论如何,我会避免将 JSON 属性 设置为 String() 构造函数。