typescript - 如何从 NestJS 的 GraphQL 解析器内部设置会话密钥?
问题描述
我正在发现 Nest.js,我想使用 GraphQL 设置一个基于 cookie 的身份验证系统。
我已经安装了 express-session 中间件,这里是配置:
main.ts
app.use(
session({
store: new redisStore({
client: redis
} as any),
name: 'qid',
secret: SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: !isDev,
maxAge: 1000 * 60 * 60 * 24 * 7 * 365
}
})
)
它工作正常,因为当我这样做时:
app.use((req: any, res: any, next: any) => {
// Debug purpose
req.session.userId = '42'
next()
})
cookie 已添加。
现在我有两个突变,register和login。在登录突变中(或在 userService 中),在我找到一个用户后,我想做类似的事情,req.session.userId = user.id
但我找不到这样做的方法。
我试图添加@Context() ctx
到我的突变中。如果我控制台日志 ctx,它包含我期望的所有内容(例如 req.session.id)
但如果我这样做ctx.req.session.userId = 'something'
了,cookie 就没有设置!
这是我的突变:
用户解析器.ts
@Mutation('login')
async login(
@Args('email') email: string,
@Args('password') password: string,
@Context() ctx: any
) {
console.log(ctx.req.session.id) // Show the actual session id
ctx.req.session.userId = 'something' // Do not set any cookie
return await this.userService.login(email, password)
}
}
我完全迷路了,我真的需要帮助,我很想了解发生了什么。我知道我可能做错了,但我对 Nest 和 GraphQL 都是新手。
谢谢你们...
解决方案
几天后我发现了这个问题......而且它是......
GraphQL Playground -> Settings -> 添加“request.credentials”:“include”(并且没有“omit”)
希望它会帮助某人..
推荐阅读
- javascript - Https请求node.js
- emacs - 如何为所有 Emacs 备份文件设置最大总大小?
- reactjs - 反应部署和搜索引擎问题
- java - 学习 Java 类和方法,在测试我的代码时遇到此错误
- python - pandas 中基于 2 列条件的条件运行计数(根据时间戳计算队列中的人数)
- odoo - Odoo KeyError:“set_scrollTop”和“ir.actions.do_nothing”
- python - 如何通过使用其他列表的值将索引插入第一个列表,将一个列表的值插入另一个列表?(Python)
- python - Python遍历文件夹中的每个文件以剪切部分视频
- c++ - 我无法显示文件的第一行
- gcc - 这个编译器标志实现了什么?