0
votes

When sending OPTIONS request, middleware doesn't get triggered.

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

If I were to change RequestMethod.OPTIONS to RequestMethod.ALL, it would get triggered on all requests, except OPTIONS.

Is that by design? If so, how do we workaround it when we want to specifically trigger middleware for OPTIONS request.

Example middleware:

@Injectable()
export class CorsMiddleware implements NestMiddleware {
  resolve(...args: any[]): MiddlewareFunction {
    return (req, res, next) => {
      console.log("testing ????", req.method);
      next && next();
    };
  }
}
1
I think this might be better suited as an issue if you have a minimal repo to reproduce it with. github.com/nestjs/nest/issuesKim Kern
Is there a different middlware already active that intercepts OPTIONS ?Evert
In fact, it appears it's impossible to handle preflights requests in Nestjs at allKunok
We handle CORS using interceptor without a problem.Karol Samborski
@KarolSamborski can you provide example of your interceptor and which Nestjs version are you using?Kunok

1 Answers

0
votes

Instead of using middleware you can try adding interceptor:

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

In order to use it you need also add a decorator above your controller class:

@UseInterceptors(CorsInterceptor)
export class SimpleController {
}