1

我有登录路线,返回用户:

@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);
}

链接到源代码。

4

1 回答 1

3

您必须@Res() reply从控制器功能中删除。一旦你注入response对象,许多嵌套功能就会停止工作,例如拦截器。

@Post('login')
async login(@Body() user: LoginRequest): Promise<User> {
    return this.authService.validateUser(user.email, user.password);
}

您可以使用拦截器来动态设置 cookie。

于 2019-05-02T09:20:20.463 回答