Nest.js-未在OPTIONS请求中触发中间件

时间:2019-03-25 14:41:37

标签: typescript nestjs

发送OPTIONS请求时,不会触发中间件。

export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(CorsMiddleware).forRoutes({
      path: "*",
      method: RequestMethod.OPTIONS
    });
  }
}

如果我将RequestMethod.OPTIONS更改为RequestMethod.ALL,它将在除OPTIONS之外的所有请求上触发。

这是设计使然吗?如果是这样,当我们要为OPTIONS请求专门触发中间件时,我们该如何解决。

中间件示例:

@Injectable()
export class CorsMiddleware implements NestMiddleware {
  resolve(...args: any[]): MiddlewareFunction {
    return (req, res, next) => {
      console.log("testing ", req.method);
      next && next();
    };
  }
}

1 个答案:

答案 0 :(得分:0)

您可以尝试添加拦截器来代替使用中间件:

@Injectable()
export class CorsInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        const request: IncomingMessage = context.switchToHttp().getRequest();
        const response: ServerResponse = context.switchToHttp().getResponse();

        if ('access-control-request-headers' in request.headers) {
            response.setHeader('access-control-request-headers', request.headers['access-control-request-headers']);
        }

        if ('access-control-request-method' in request.headers) {
            response.setHeader('access-control-request-method', request.headers['access-control-request-method']);
        }

        response.setHeader('access-control-allow-origin', '*');

        return next.handle();
    }
}

要使用它,还需要在控制器类上方添加装饰器:

@UseInterceptors(CorsInterceptor)
export class SimpleController {
}