Apollo GraphQL Playground获取登录用户名称失败及getUserId问题排查
错误核心原因
这个错误是因为你在getUserId函数中尝试读取一个undefined对象的authorization属性——大概率是没有正确从Apollo的context中获取请求对象(req),或是调用getUserId时传错了参数。
修复步骤
1. 确保Apollo Server将请求对象注入Context
在初始化Apollo Server的代码里,必须把请求对象req传入context,这样resolver才能拿到请求头信息:
// Apollo Server初始化示例代码 import { ApolloServer } from 'apollo-server'; import typeDefs from './schema.graphql'; import resolvers from './resolvers'; import prisma from './prisma'; const server = new ApolloServer({ typeDefs, resolvers, // 将req和prisma注入context context: ({ req }) => ({ req, prisma }), }); server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
2. 修改getUserId函数,从Context中读取请求头
在utils.js中,getUserId要接收context作为参数,从context.req.headers里提取Authorization头:
// utils.js import jwt from 'jsonwebtoken'; export const getUserId = (context) => { // 从context的req对象中获取Authorization头 const authHeader = context.req.headers?.authorization; if (!authHeader) { throw new Error('未提供Authorization请求头'); } // 拆分Bearer token格式的字符串 const token = authHeader.split(' ')[1]; if (!token) { throw new Error('Authorization格式错误,应为Bearer <token>'); } // 验证JWT并解析出用户ID const decoded = jwt.verify(token, process.env.JWT_SECRET); return decoded.userId; };
3. 在me Resolver中正确传入Context参数
在src/resolvers/Query.js的me resolver里,调用getUserId时传入context:
// src/resolvers/Query.js export const Query = { me: async (parent, args, context) => { // 传入context到getUserId const userId = getUserId(context); // 通过Prisma查询当前用户 return context.prisma.user.findUnique({ where: { id: userId }, }); }, };
4. 在Playground中正确设置请求头
调用me query前,在Playground的Headers标签中添加Authorization头,格式如下:
{ "Authorization": "Bearer 你的登录token" }
关键注意点
getUserId的参数必须是context,而非直接的req——Apollo resolver的第三个参数是context,里面包含了我们注入的req对象。- 务必确认context已正确注入
req,否则context.req会是undefined,依然会触发相同错误。
内容的提问来源于stack exchange,提问作者JohnBradens
相关产品推荐
相关产品推荐

