CORS (Cross-Origin Resource Sharing) is a security feature in web browsers that blocks requests from different origins (domains) unless the server explicitly allows them.
By default, browsers block requests if:
- Your frontend (React, Angular, etc.) is on http://localhost:3000
- Your backend API is on http://localhost:5000
- The backend does not allow CORS, so the browser blocks the request
Solution: Use cors Middleware in Express
The cors package helps enable cross-origin requests in Express.
Installation:
npm install cors
Basic Usage in Express:
const express = require('express');
const cors = require('cors');
const app = express();
// Enable CORS for all requests
app.use(cors());
app.get('/data', (req, res) => {
res.json({ message: 'CORS enabled!' });
});
app.listen(5000, () => console.log('Server running on port 5000'));
Allow Specific Origins Only
If you want to restrict which frontend domains can access your API:
app.use(cors({
origin: 'http://localhost:3000' // Allow only this frontend
}));
Allow Multiple Origins
For multiple domains:
const allowedOrigins = ['http://localhost:3000', 'https://mywebsite.com'];
app.use(cors({
origin: function (origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
}));
Enable CORS for Specific Routes Only
app.get('/public', cors(), (req, res) => {
res.json({ message: 'Public data, CORS enabled' });
});
app.get('/private', (req, res) => {
res.json({ message: 'Private data, CORS disabled' });
});
Allow Specific Methods & Headers
You can customize allowed HTTP methods and headers:
app.use(cors({
origin: '*', // Allow all origins
methods: ['GET', 'POST', 'PUT', 'DELETE'], // Allow only these HTTP methods
allowedHeaders: ['Content-Type', 'Authorization'] // Allow specific headers
}));
Why Use cors?
β
Fixes CORS errors when calling APIs from different origins
β
Allows frontend to talk to backend
β
Can restrict or allow specific domains
β
Supports custom headers and methods
Let me know if you need CORS settings for production! π
Top comments (0)