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

如何解决GraphQL Nest.js中response.cookie is not a function错误

问题原因

  1. Response类型导入错误:你可能导入了Node.js原生http.Response而非Express框架的Response对象,只有Express的Response才内置cookie()方法。
  2. GraphQL上下文传递的res未正确利用:虽然GraphQLModule配置中已将res传入上下文,但resolver里未正确使用该对象。

解决方案

方案一:修正Response类型导入

在account.resolver.ts中,替换为Express的Response类型:

// 替换原有Response导入
import { Response } from 'express';

async login(
    @Res({ passthrough: true }) response: Response,
    @GetExecutionContext() context: GqlExecutionContext,
    @Args('AccountInput') AccountInput: AccountInput
): Promise<AccountTokenOutput> {
    response.cookie('refreshtoken', 'refreshtoken');
    return await this.accountService.login(AccountInput, context);
};

方案二:从GraphQL上下文直接获取res对象

利用已配置的上下文传递的res对象:

import { Response } from 'express';

async login(
    @Args('AccountInput') AccountInput: AccountInput,
    @Context() context: { res: Response }
): Promise<AccountTokenOutput> {
    context.res.cookie('refreshtoken', 'refreshtoken');
    return await this.accountService.login(AccountInput, context);
};

额外注意事项

  • 确认cookie-parser中间件已正确注册(你的main.ts中已添加app.use(cookieParser());,此部分无需修改)。
  • 避免重复配置CORS:GraphQLModule和main.ts中都配置了CORS,建议统一保留一处即可,防止冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 15:10:28