【问题标题】:Unable to set cookie in NestJS GraphQL无法在 NestJS GraphQL 中设置 cookie
【发布时间】:2020-11-21 12:30:20
【问题描述】:

我们有一个 NestJS GraphQL 服务器正在运行,我们正在尝试在拦截器中设置一个 httpOnly cookie。 如果我们通过 Postman 调用突变,该设置似乎可以工作,在 cookie 选项卡中显示 cookie。 但是从 Playground 调用突变,浏览器中没有 cookie 的踪迹。 即使在警卫中访问request.cookies 属性也不会给我们任何结果。我们做错了什么?

服务器基于fastify,我们使用fastify-cookie 库来设置cookie。

拦截器代码为:

@Injectable()
export class AccessTokenCookieInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler<AccessTokens>): Observable<any> {
    const ctx = GqlExecutionContext.create(context);
    const response: FastifyReply = ctx.getContext().response;
    return next.handle().pipe(
      tap(data => {
        response.setCookie('my_cookie', JSON.stringify(data), {
          httpOnly: true,
          path: '/',
        });
      }),
    );
  }
}

GQL 模块:

GraphQLModule.forRoot({
  autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
  sortSchema: true,
  context: ({ request, reply }) => {
    return {
      request,
      response: reply,
    };
  },
  ...
}),

我们读取 cookie 的守卫:

@Injectable()
export class AccessTokenGuard implements CanActivate {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const ctx = GqlExecutionContext.create(context);
    const request = ctx.getContext().request;

    const cookie = request.cookies['my_cookie'];
    const tokens: AccessTokens = JSON.parse(cookie);

    request.finxTokens = tokens;

    return true;
  }
}

感谢您的帮助!

【问题讨论】:

    标签: cookies graphql nestjs


    【解决方案1】:

    1 - 您需要将cors 设置添加到您的 GQLModule;

    GraphQLModule.forRoot({
      ...
       cors: {
         credentials: true,
         origin: true
       }
    })
    

    2 - 在您的 apollo 客户端设置中告诉您的网络接口将 cookie 与每个请求一起发送。你只需要传递credentials 选项;

     const httpLink = new HttpLink({ uri: 'graphql', credentials: 'include' });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-19
      • 2019-11-06
      • 2021-05-26
      • 2021-12-19
      • 2020-06-29
      • 2011-12-27
      • 2015-05-20
      • 2013-05-02
      相关资源
      最近更新 更多