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
Make sure you have
cors
is installed if not then install with :Then:
There are severel reasons that this error can be display.
For example if you defined localhost:3000/api/user and call it as localhost:3000/user then browser will display this error