is there any thing can affect cors at localhost

70 Views Asked by At

I am building Full stack website with ReactJS with vite, NestJS, and typescript I am facing some issues with cors I did setup cors at the backend to accept any request from the front end localhost:5173

this is main.ts in NestJS

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

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

  app.enableCors({
    origin: 'http://localhost:5173', // specify the allowed origin
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', // specify the allowed HTTP methods
    credentials: true, // enable credentials (cookies, authorization headers)
  });

  await app.listen(3000);
}
bootstrap();

I am getting this error

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:3000/api/auth-client/sign-out. (Reason: CORS request did not succeed). Status code: (null).

the function that calls the API

const ClientAuthSignOut = async (userAccessToken: string) => {
  const response = await fetch(`${baseURL}/auth-client/sign-out`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${userAccessToken}`,
    },
  });
  return await response.json();
};

this function is called somewhere else

const handleLogout = async () =>
  try {
    const data = await ClientAuthSignOut(token);
    if (data.message === "signed out successfully") {
      dispatch(UNSET_AUTH_DATA());
      localStorage.removeItem("user");
    }
  } catch (error) {
    alert("Something went wrong. Please try again");
  }
};

the problem was that it worked fine at first but after that, it started throwing this error and the only way to fix it was by restarting my laptop I am using a Macbook Pro M2 pro

is there anything that may affect cors for localhost

I am calling an api I built with nestJS

Calling api from my backend should return JSON data but I can not call my api because of cors The only way I can fix it is by restarting my laptop

1

There are 1 best solutions below

0
Abdulkader Safi On

Sorry for disturbing but I found the issue somehow 2 servers were working on port 3000 which is strange I use Obsidian for note taking, project management, and todo lists and one of the plugins called Slide Preview was running on localhost:3000 this plugin allows me to create presentations using markdown and there is a button to run the presentation on the browser I noticed that it was running on port 3000 like my NestJS backend So I solved the issue by changing the port of the plugin from the settings