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.
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.
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!
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.
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();
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,
}});
.....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With