CORS keeps blocking request during preflight on the browser

I'm trying to access my API from the browser but the request is blocked by CORS, with the error "Access to XMLHttpRequest at 'http://localhost/3001/auth/login/staff' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource." I tried adding Access-Control-Allow-Origin to allow headers in Cors config but it's not working, I've tested the endpoint on Postman and it works, I'm attaching screenshots of my code(I don't know how to setup nestjs in code sandbox), here's the link to GitHub https://github.com/johnpatrick254/School-Management-System/ on client-webapp branch Any assistance will be highly appreciated!
GitHub
GitHub - johnpatrick254/School-Management-System: A fullstack schoo...
A fullstack school management system. Contribute to johnpatrick254/School-Management-System development by creating an account on GitHub.
No description
No description
No description
No description
No description
9 Replies
dys 🐙
dys 🐙11mo ago
It looks like app.enableCors isn't having any effect. In the browser, I'd look in the Network tab and then the Headers for the resource in question to verify there is no Access-Control-Allow-Origin. (Your sample deployment 404s currently.) Unfortunately, I don't know Nest.js, so I can't tell you how to fix it. According to Phind, your code looks reasonable.
Joao
Joao11mo ago
Check the logs and see if the local requests are coming as "localhost" or as "127.0.0.1", and use that in your origin field for cors. Here's an example of how I have it setup for a Nest.js project:
app.enableCors({
allowedHeaders: ['Content-Type', 'Authorization'],
methods: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'],
origin: isProduction(MODE) ? false : '*',
preflightContinue: false,
optionsSuccessStatus: 204,
});
app.enableCors({
allowedHeaders: ['Content-Type', 'Authorization'],
methods: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'],
origin: isProduction(MODE) ? false : '*',
preflightContinue: false,
optionsSuccessStatus: 204,
});
Note that since it's for development, I allow everything just to make my life easier 😄
John Patrick Onyango
sorry, I just redeployed, I've updated the deployment link https://school-management-system-eosin.vercel.app/, and here's the link to the full collection https://www.postman.com/planetary-resonance-710765/workspace/school-management-system/collection/25675970-cd560eb6-9bc6-45fc-b236-d3772d0d06e7?action=share&creator=25675970&active-environment=25675970-02aa1a23-8564-40a2-9fe1-272b28f20760 ...and now the request is accepted in localhost but rejected on the deployed version, I inspected the headers and noticed the deployed version returns no response headers despite having the same code as the one I'm running locally
No description
John Patrick Onyango
this works, but since I use httpOnly cookies I can't use a wildcard for origin, and disabling preflight is not recommended...however I'll use this anyway for development as I figure out what the issue is
Nihan
Nihan11mo ago
Hey, so I can't really find the links for the report but Chromium won't allow you to use localhost as origin. I recommend using * for dev and in production using the actual domain. Technically you can set up a different name instead of the term localhost to point to your own machine but not sure if you need it..
John Patrick Onyango
thanks for the input, however, I almost gave up because now it works locally but the request is rejected on the deployed version
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { AllExceptionsFilter } from './lib/allExceptionFilter.filter';
import { ValidationPipe } from '@nestjs/common';
import cookieParser from 'cookie-parser';
import { ConfigService } from '@nestjs/config';
import { logger } from './lib/logger';
import helmet from 'helmet';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
const FRONTED_URL = configService.get('FRONTEND_URL');
const PORT = configService.get('PORT');
const ENV = configService.get('ENV');
if (ENV === "PROD") app.use(helmet());
app.enableCors({
origin: ['http://localhost:3000', FRONTED_URL],
credentials: true,
allowedHeaders: ['Access-Control-Allow-Origin', 'Content-Type', 'Accept'],
});
app.use(cookieParser());
app.useGlobalPipes(new ValidationPipe());
app.useGlobalFilters(new AllExceptionsFilter());
await app.listen(PORT, async () => {
logger.log(`✅ APP RUNNING ON : ${await app.getUrl()} 🚀`)
});
}
bootstrap();
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { AllExceptionsFilter } from './lib/allExceptionFilter.filter';
import { ValidationPipe } from '@nestjs/common';
import cookieParser from 'cookie-parser';
import { ConfigService } from '@nestjs/config';
import { logger } from './lib/logger';
import helmet from 'helmet';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
const FRONTED_URL = configService.get('FRONTEND_URL');
const PORT = configService.get('PORT');
const ENV = configService.get('ENV');
if (ENV === "PROD") app.use(helmet());
app.enableCors({
origin: ['http://localhost:3000', FRONTED_URL],
credentials: true,
allowedHeaders: ['Access-Control-Allow-Origin', 'Content-Type', 'Accept'],
});
app.use(cookieParser());
app.useGlobalPipes(new ValidationPipe());
app.useGlobalFilters(new AllExceptionsFilter());
await app.listen(PORT, async () => {
logger.log(`✅ APP RUNNING ON : ${await app.getUrl()} 🚀`)
});
}
bootstrap();
i disabled helmet in development because it was blocking sharing httponly cookies through HTTP
Nihan
Nihan11mo ago
Okay first of all, Don't give up Lol
Joao
Joao11mo ago
I'm not sure what's up but maybe at this point it's worth heading over the Nest.js server and ask over there? I'm also curious about this if you find out please update this thread 😄 https://discord.gg/nestjs
John Patrick Onyango
okay, thanks
Want results from more Discord servers?
Add your server