CORS (Cross-Origin Resource Sharing) is a security feature in web browsers that prevents making requests to a different origin (domain, protocol, or port) than the one from which the web page was loaded.
If you see an error like this in the console:
Access to fetch at '<http://localhost:4000/api/data>' from origin '<http://localhost:3000>' has been blocked by CORS policy
It means the backend does not allow requests from the frontend’s origin.
By default, browsers block cross-origin requests for security reasons.
For example, if your frontend (http://localhost:3000
) tries to fetch data from a backend (http://localhost:4000
), the browser blocks it unless the backend explicitly allows it.
In your Node.js + Express server, install and use the cors
middleware:
npm install cors
Then modify server.js
:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors()); // Allows all origins (not recommended for production)
// OR specify allowed origins
app.use(cors({
origin: '<http://localhost:3000>' // Allow only this frontend
}));
app.get('/api/data', (req, res) => {
res.json({ message: "CORS issue fixed!" });
});
app.listen(4000, () => console.log('Server running on port 4000'));
example.com
), CORS is not needed. like next js