我在快速 session 方面遇到问题。我正在使用 typescript :
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/具有相同 session ID 的完全相同的 session cookie。
最佳答案
preHandler
钩子(Hook)会在每个请求中运行,因此您每次都会覆盖 sessionData:
app.addHook('preHandler', (request, _reply, next) => {
request.session.sessionData = {userId: String, name: String, email: String, password: String, loggedOn: Date};
next();
})
因此,name
是 String
构造函数,它被字符串化为输出。
您应该检查 session :
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()
构造函数。
关于node.js - fastify session 抛出一些我不明白的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62180315/