What is a CORS Error, and How to Fix It in an Express.js Environment?
Every web developer has encountered the red error message flashing on the console at least once: "Access to fetch at... has been blocked by CORS policy". This error occurs when the frontend running in the browser (e.g., localhost:3000) tries to request data from a backend located on a different domain or port (e.g., localhost:8080).
CORS (Cross-Origin Resource Sharing) is a security mechanism enforced by browsers (SOP - Same-Origin Policy). Its purpose is to prevent malicious website scripts from stealing data from another website on behalf of the user.
Resolving the CORS Error in a Node.js / Express Environment
Since CORS is checked by the browser, we need to indicate on the server side in the response headers (Headers) which origins we allow access to. In an Express.js environment, this can be done most easily using the official cors middleware:
const express = require('express');
const cors = require('cors');
const app = express();
// Allowing access for a specific domain (Secure approach)
const corsOptions = {
origin: 'https://simplesolution.ro',
optionsSuccessStatus: 200
};
app.use(cors(corsOptions));
app.get('/api/v1/data', (req, res) => {
res.json({ message: "Successful, CORS-safe data connection!" });
});
app.listen(8080, () => console.log('Server is running on port 8080'));
During the development phase, app.use(cors()) without parameters allows any origin (*), but in a production environment, as in the example above, we should always restrict it to our own frontend domain.