I have a mistake in a project on Nest JS deployed on EC2 with Nginx, when i make a call from an external frontend to the API the API returns CORS error.
Im checked docs, blogs, tutorial and dont work still. How i can fix this error?
I tried with “origin”: “*” and “origin”: domain”,
This is my configuration on main.ts
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { ValidationPipe } from "@nestjs/common";
import * as cookieParser from "cookie-parser";
async function bootstrap() {
// somewhere in your initialization file
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
app.use(cookieParser());
const otherAllowedHeaders = ["Authorization", "X-Requested-With"];
app.enableCors({
// "origin": "*",
origin: "https://my_domain.com",
allowedHeaders: [
"Content-Type",
"Origin",
"X-Requested-With",
"Accept",
"Authorization",
],
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
preflightContinue: false,
optionsSuccessStatus: 204,
});
await app.listen(3000);
}
bootstrap();
The nginx.conf
location / {
if ($request_method = POST) {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
}
if ($request_method = OPTIONS) {
return 208;
}
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_pass_request_headers on;
}
This is the error