Fix CORS Error in Express.js
Quickly enable CORS in your Express app to fix blocked API requests from frontend applications.
javascript
27 lines
// Install first:
// npm install cors
const express = require('express');
const cors = require('cors');
const app = express();
// Enable CORS for all routes
app.use(cors());
// Optional: restrict to specific origin
/*
app.use(cors({
origin: 'http://localhost:3000',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
credentials: true
}));
*/
app.get('/', (req, res) => {
res.json({ message: 'CORS enabled successfully!' });
});
app.listen(5000, () => {
console.log('Server running on port 5000');
});How to use: Click Copy to copy the full snippet to your clipboard. Snippets are provided as-is — always review and test code before using in production.