node.js - fastify session 抛出一些我不明白的东西

标签 node.js fastify

我在快速 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();
})

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

您应该检查 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/

相关文章:

javascript - nodejs 是否支持多线程?

node.js - nginx 有时响应 504/502 网关超时错误

typescript - 将 Typescript 类 DTO 转换为 Fastify Swagger 的 JSON 模式

node.js - 如何为 React 提供 index.html 并在相同路径处理路由?

javascript - 为什么 instanceof 在这里评估为真?

node.js - Mongodb 和 Express 从 _id 中删除项目

javascript - Node.js "Cannot read property ' 原型(prototype)“未定义”错误 - Node.js、MongoDB 和 Angularjs 书

ajv - 如何在 fastify 中使用 ajv-i18n ?

express - Cloud Run 为什么不发送 cookie?

javascript - 在 NestJS 中,有没有办法将数据从 Guards 传递到 Controller ?