【问题标题】:fastify session is throwing something that I dont understandfastify session 抛出了一些我不理解的东西
【发布时间】:2020-06-04 21:28:29
【问题描述】:

我对 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/ 时,它会显示我的随机名称,但 oldname 是下面的代码。 showmename 和 oldname 完全一样。

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

我做错了吗?因为当我转到 localhost/showmename 时,firefox 的 cookie 编辑器插件会向我显示与 localhost/ 具有相同会话 id 的完全相同的会话 cookie。

【问题讨论】:

    标签: node.js fastify


    【解决方案1】:

    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() 构造函数。

    【讨论】:

    • 您好,谢谢,我通过使用 FileStore 进行会话修复了它,但无论如何,您的回答也很有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 2013-07-12
    相关资源
    最近更新 更多