typescript - Cum pot seta cookie-uri în obiectul de răspuns într-o aplicație NestJS GraphQL?
Cum pot seta cookie-uri în obiectul de răspuns într-o aplicație NestJS GraphQL? Cod:
app.module.ts:
GraphQLModule.forRoot<ApolloDriverConfig>({
autoSchemaFile: true,
driver: ApolloDriver,
cors: {
origin: process.env.ADDRESS,
credentials: true,
},
context: ({ req, res }) => ({ req, res }),
}),
rezolvator :
@Mutation(() => token)
async login(
@Args("input") input: LoginI,
@Context() context: GraphQLExecutionContext
) {
const result = await this.authnService.login(input);
context.res.cookie("authorization", "Bearer " + result.userToken);
return result;
}
Dar nu pare să funcționeze corect.
console.log(context.res.cookies)
returnează nedefinit. De asemenea, nu există cookie-uri în instrumentele de dezvoltare ale browserului pentru clientul meu.
Răspuns #1
Pentru alte persoane care întâmpină probleme la primirea cookie-urilor în GraphQL playground, asigurați-vă că playground-ul dvs. este configurat corect. În mod implicit, request.credentials este setat la omit; schimbându-l la include va începe să includă credențialele.
const GraphQL = GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
playground: {
settings: {
"request.credentials": "include", // Otherwise cookies won't be sent
}
},
// ...
});
Răspunsul #2
The @Res() decorator is imported from the @nestjs/common, while Response from the express package.
@Post('some-route')
someHandler(@Res({ passthrough: true }) response: Response) {
# get create refreshToken
response.cookie('refreshToken', refreshToken);
}
