shahriarsajeeb / Food-Delivery-WebApp

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

CORS Error when Making Requests to NestJS Backend

Indu-Chandana opened this issue · comments

I'm encountering a CORS (Cross-Origin Resource Sharing) error when attempting to make requests from my Next.js frontend to my NestJS backend. This issue is hindering the communication between the frontend and backend of my application.

'Access to fetch at 'http://localhost:4001/graphql' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.'

To fix the CORS issue, the following code snippet should be added to the servers/apps/users/src/main.ts file in the NestJS backend:

app.enableCors({ origin: '*', });

`import { NestFactory } from '@nestjs/core';
import { UsersModule } from './users.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';

async function bootstrap() {
const app = await NestFactory.create(UsersModule);

app.useStaticAssets(join(__dirname, '..', 'public'));
app.setBaseViewsDir(join(__dirname, '..', 'servers/email-templates'));
app.setViewEngine('ejs');

app.enableCors({
origin: '*',
});

await app.listen(4001);
}
bootstrap();
`
This tutorial is excellent, but it seems that some parts are missing. The instructor makes changes to the code without recording them.