16

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.

Francesco Borzi
  • 56,083
  • 47
  • 179
  • 252

3 Answers3

22

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();
Kamil Myśliwiec
  • 8,548
  • 2
  • 34
  • 33
Francesco Borzi
  • 56,083
  • 47
  • 179
  • 252
  • 2
    The cors is a built-in feature, see here for more details: https://docs.nestjs.com/techniques/cors :) – Kamil Myśliwiec May 16 '18 at 08:30
  • 3
    @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 wrong – chaostheory Sep 28 '18 at 18:08
  • @KamilMyśliwiec where did the CORS documentation go on the nestjs documentation site? it appears there is a redirect now – Chris Cooley Oct 03 '18 at 20:40
10

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,
  }});
.....
mumblesNZ
  • 556
  • 4
  • 6
2

Anyone still looking for the answer

app.enableCors();