Express 会话 - 无法设置未定义的属性(设置“用户”)
我有一个问题。在 Express 和 GraphQL 中设置会话时。
配置:
app.use(
session({
name: "user",
secret:
"test",
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
expires: 60 * 60 * 10000,
},
})
)
app.use(
cors({
origin: ["http://localhost:3000"],
methods: ["GET", "POST"],
credentials: true,
})
)
app.use(express.json())
app.use(cookieParser())
app.use(bodyParser.urlencoded({ extended: true }))
GraphQL 路由(如何获取 req 作为参数):
graphqlHTTP({
schema,
graphiql: true,
context: (req: any) => ({
...req,
}),
})
如何定义会话:
const getId = await Users.findOne({ user_email: email })
const ID = getId?.user_id
req.session.user = ID
console.log("ee " + req.session.user)
检查会话是否存在:
try {
if (req.session.user) {
return {
success: true,
user_id: req.session.user,
}
} else {
return { success: false }
}
} catch (error) {
console.log(error)
}
并且返回Cannot set properties of undefined (setting 'user')
问题是什么? 是这样的,我如何获取 req 作为参数,还是其他什么?
I have a problem. While setting up the session in Express and GraphQL.
Config:
app.use(
session({
name: "user",
secret:
"test",
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
expires: 60 * 60 * 10000,
},
})
)
app.use(
cors({
origin: ["http://localhost:3000"],
methods: ["GET", "POST"],
credentials: true,
})
)
app.use(express.json())
app.use(cookieParser())
app.use(bodyParser.urlencoded({ extended: true }))
GraphQL route(How I get req as a parameter):
graphqlHTTP({
schema,
graphiql: true,
context: (req: any) => ({
...req,
}),
})
How I define a session:
const getId = await Users.findOne({ user_email: email })
const ID = getId?.user_id
req.session.user = ID
console.log("ee " + req.session.user)
Check if session is there:
try {
if (req.session.user) {
return {
success: true,
user_id: req.session.user,
}
} else {
return { success: false }
}
} catch (error) {
console.log(error)
}
And it returns Cannot set properties of undefined (setting 'user')
What is the problem?
Is it that, how I get req as a parameter, or anything else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论