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.
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.
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,
}});
.....
© 2022 - 2024 — McMap. All rights reserved.