在Apollo Server 4中,如果在成功登录后访问context.user返回为空,可能是因为没有正确设置并传递用户信息。下面是一个可能的解决方法:
// 登录成功后设置用户信息
const user = { id: 1, name: "John" };
// 将用户信息存储在上下文中
const context = { user };
context选项。const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
// 在这里返回上下文对象,包括用户信息
return { user: req.user };
},
});
// 使用中间件验证登录状态,并将用户信息赋值给req.user
app.use((req, res, next) => {
// 验证登录状态
const isAuthenticated = true; // 假设已验证登录
if (isAuthenticated) {
// 设置用户信息
req.user = { id: 1, name: "John" };
}
next();
});
请注意,上述代码示例中的用户信息是假设的,您需要根据您的应用程序逻辑和数据结构来设置和传递正确的用户信息。