Getting 404 Not Found on OPTIONS with NestJS
Asked Answered
Y

3

20

I'm new to NestJS and on every route my web app is trying to query, it fails on the OPTIONS request, getting:

{"statusCode":404,"error":"Not Found","message":"Cannot OPTIONS /authenticate"}

however trying a direct GET or POST request works fine.

Yetac answered 15/5, 2018 at 15:37 Comment(0)
Y
27

after some researches I've realised that I simply needed to enable CORS (Access-Control-Allow-Origin), which I can do by editing my main.ts and passing cors: true to the NestFactory.create options (second parameter).

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true });
  await app.listen(3000);
}
bootstrap();
Yetac answered 15/5, 2018 at 15:37 Comment(3)
The cors is a built-in feature, see here for more details: docs.nestjs.com/techniques/cors :)Stacy
@KamilMyśliwiec This still doesn't work for me. Neither does app.enableCors(). All HTTP OPTIONS requests just fail with a 404. Not sure what's wrongCatnip
@KamilMyśliwiec where did the CORS documentation go on the nestjs documentation site? it appears there is a redirect nowSandberg
S
11

Some extra info on CORS, if you enable it via:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true });
  await app.listen(3000);
}
bootstrap();

This will allow Cross Origin Requests from any domain. Which is generally not security best practice.

If you want to allow CORS to intercept your preflight requests, but also only allow origin requests from within the server, you can use this config:

.....
  const app = await NestFactory.create(ApplicationModule, {cors: {
    origin: true,
    preflightContinue: false,
  }});
.....
Syntax answered 5/6, 2018 at 12:40 Comment(0)
S
2

Anyone still looking for the answer

app.enableCors();
Stoker answered 26/8, 2021 at 19:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.