我有登录路线,该路线返回了用户:
@Post('login')
async login(@Body() user: LoginRequest, @Res() reply): Promise<User> {
const foundUser = await this.authService.validateUser(user.email, user.password);
reply.setCookie('t', foundUser._id, { path: '/' });
// reply.send(foundUser);
return foundUser;
}
我的问题是,除非我reply.send(foundUser);
我正在使用具有允许cors起源的代理:
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
// enable cors for static angular site.
const corsOptions = {
origin: 'http://localhost:4200',
optionsSuccessStatus: 200,
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
};
app.register(require('fastify-cors'), corsOptions);
// enable cookie for auth.
app.register(require('fastify-cookie'));
// validate types and extra
app.useGlobalPipes(new ValidationPipe({ forbidUnknownValues: true }));
await app.listen(3000);
}
Link到源代码。
答案 0 :(得分:2)
您必须从控制器功能中删除@Res() reply
。注入response
对象后,许多嵌套功能就会停止工作,例如拦截器。
@Post('login')
async login(@Body() user: LoginRequest): Promise<User> {
return this.authService.validateUser(user.email, user.password);
}
您可以使用interceptor来动态设置cookie。