skip to Main Content

My client (React app) and server (Node project) run on different ports (3000 and 5000, respectively). I’m trying to make an API request from the frontend to the backend, and am getting this error message in the frontend console:

Access to XMLHttpRequest at 'http://localhost:5000/period' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have tried installing the cors module and using it like so in my NodeJS server’s index.js file (I have also tried specifying ‘http://localhost:3000’ instead of ‘*’):

const express = require('express');
const cors = require("cors");
const app = express();
app.use(cors({ origin: '*' }));

This didn’t seem to change anything even after restarting the client and server. This is how I’m making the API request with axios in my React code:

useEffect(() => {
        axios.get(`${import.meta.env.VITE_BASE_URL}:${import.meta.env.VITE_SERVER_PORT}/version`)
            .then(res => {
                console.log("Versions:")
                console.log(res);
            });
}, []);

2

Answers


  1. Make sure you have cors is installed if not then install with :

    npm i cors
    

    Then:

    const express = require('express');
    const cors = require("cors");
    const app = express();
    
    // Enable CORS for all routes
    app.use(cors());
    
    Login or Signup to reply.
  2. There are severel reasons that this error can be display.

    • First make sure that the request url and the defined URL in the server is equal

    For example if you defined localhost:3000/api/user and call it as localhost:3000/user then browser will display this error

    • secondly make sure that you have installed used packages to install cors use npm i cors
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search