【问题标题】:unable to get cookies from ExecutionContext无法从 ExecutionContext 获取 cookie
【发布时间】:2021-05-18 07:46:34
【问题描述】:

我正在使用nestjs 和graphql 获取cookie。通过在模块上设置 graphql 并创建 UseGuard 创建验证 cookie 的逻辑时出现问题。

据说GqlExecutionContext可以用来导入请求的cookie,但是还是继续返回null。我也无法通过switchToHttp 提取cookie。

app.module.ts

@Module({
    imports: [
        TypeOrmModule.forRoot(),
        GraphQLModule.forRoot({
            autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
            context: ({ req }) => ({ req }),
            cors: {
                credentials: true,
                origin: true,
            },
        }),
        AuthModule,
        UserModule,
        FormModule,
    ],
    providers: [DateScalar],
})
export class AppModule {}

guards/login.guard.ts

@Injectable()
export class LoginGuard implements CanActivate {
    constructor(private readonly authService: AuthService) {}

    canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
        console.log('!LoginGuard!');
        const ctx = GqlExecutionContext.create(context);
        const request = ctx.getContext();
        const token = request.cookies ? request.cookies['x-access-token'] : null;
        console.log(token); // here throws null
        /*
        Token Validate Logic Here
        */
        return true;
    }
}

form/form.resolver.ts

@Resolver()
export class FormResolver {
    constructor(private readonly formService: FormService) {}

    @UseGuards(LoginGuard)
    @Query(() => Form)
    async getFormById(@Args('id') id: number): Promise<Form> {
        return await this.formService.getOne(id);
    }

    @UseGuards(LoginGuard)
    @Mutation(() => Form)
    async createForm(@Args('form') form: FormInput): Promise<Form> {
        return await this.formService.create(form);
    }
}

我只想将 Guard 应用于特定的解析器,因此我使用了 UseGuard 而不是全局中间件。我的方法有问题吗?

【问题讨论】:

  • 您是否使用任何中间件来解析传入的cookie? ctx.getContext().request.cookies呢?
  • 它仍然抛出“无法读取未定义的属性'cookies'”,并在中间件中使用cookie-parser。
  • 抱歉。 ctx.getContext().req.cookies。您将req 对象附加到GraphQLModule 中context 的req 属性
  • 谢谢,但 ctx.getContext().req.cookies 返回 null 对象。开发者工具上显示cookie,不知道为什么返回null。
  • 如果您使用 ctx.getContext().req.cookies 和 cookie-parse 中间件,我觉得一切都很好。我可以看看你的 main.ts 吗?

标签: typescript graphql nestjs


【解决方案1】:

我意识到后端没有问题。请求是通过 GraphQL Playground 测试的,应该已经修改了“request.credentials”选项。

{
  "request.credentials": "same-origin",
}

When the option set to "omit" is modified as follows, header information is sent together.

【讨论】:

    猜你喜欢
    • 2018-12-19
    • 1970-01-01
    • 2021-10-12
    • 2014-05-09
    • 2012-08-10
    • 2023-02-14
    • 2020-07-19
    • 2022-01-12
    • 2020-07-13
    相关资源
    最近更新 更多