控制器不重播就不会返回结果。使用fastify平台发送

时间:2019-05-02 02:47:10

标签: javascript node.js typescript nestjs fastify

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

@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到源代码。

1 个答案:

答案 0 :(得分:2)

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

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

您可以使用interceptor来动态设置cookie。