You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GraphQL+Express用户认证问题:me查询返回空值

问题分析与修复方案

你的代码存在两个关键问题导致me查询无法返回用户数据:

1. Authorization头格式未正确处理

前端传递的认证token通常遵循Bearer <token字符串>的格式,但你的代码直接将整个authorization头内容传入jwt.verify,会导致JWT解析失败,最终context中的user对象为空。

2. JWT Payload字段不匹配

在登录/注册时,你用jwt.sign({ userId: user.id }, ...)将用户ID存在userId字段中,但在me查询的resolver里,你尝试用user.id去查询用户——解析后的JWT payload里根本没有id字段,只有userId,所以查询会返回空值。


修复代码

第一步:修正Context中的Token解析逻辑

修改context函数,正确提取纯token并映射字段:

const context = ({ req }) => {
    // 提取Bearer前缀后的纯token
    const authHeader = req.headers.authorization;
    const token = authHeader ? authHeader.split(' ')[1] : '';
    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        // 将JWT中的userId映射为resolver期望的id字段
        return { prisma, user: { id: decoded.userId } };
    } catch (error) {
        return { prisma };
    }
};

第二步:确保前端请求头正确传递Token

在执行me查询时,必须在请求头中加入:

Authorization: Bearer <登录/注册返回的token>

可选优化:统一Payload字段

如果你不想在context中映射字段,也可以直接修改me查询的resolver,使用JWT中的userId字段查询:

me: async (_, __, { prisma, user }) => {
    if (!user) {
        throw new AuthenticationError('You must be logged in');
    }

    try {
        const userData = await prisma.user.findUnique({
            where: { id: user.userId }, // 改为使用userId字段
        });
        return userData;
    } catch (error) {
        throw new Error('Unable to retrieve user data');
    }
},

内容的提问来源于stack exchange,提问作者ELLEpHANT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 18:35:01