如何解决GraphQL Nest.js中response.cookie is not a function错误
问题原因
- Response类型导入错误:你可能导入了Node.js原生
http.Response而非Express框架的Response对象,只有Express的Response才内置cookie()方法。 - 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
相关产品推荐
相关产品推荐

