【发布时间】: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