Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting 404 Not Found on OPTIONS with NestJS

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.

like image 891
Francesco Borzi Avatar asked May 15 '18 15:05

Francesco Borzi


People also ask

Is it possible to show a 404 page for not found routes in NestJS?

No, you can define it as a global exepction handler. I'll edit my answer. When I use this, all the validation pipes are failing. I've added an argument to the Catch() -decorator to only catch NotFoundException errors.

What server does NestJS use?

Under the hood, Nest makes use of robust HTTP Server frameworks like Express (the default) and optionally can be configured to use Fastify as well!

What is request in NestJS?

Request object Handlers often need access to the client request details. Nest provides access to the request object of the underlying platform (Express by default). We can access the request object by instructing Nest to inject it by adding the @Req() decorator to the handler's signature.


2 Answers

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();
like image 96
Francesco Borzi Avatar answered Oct 19 '22 20:10

Francesco Borzi


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,
  }});
.....
like image 10
mumblesNZ Avatar answered Oct 19 '22 19:10

mumblesNZ