Table Of Contents
Problem
Your frontend application gets a CORS (Cross-Origin Resource Sharing) error when making API requests to your Express.js server, showing "Access to fetch has been blocked by CORS policy".
Solution
const express = require('express');
const cors = require('cors');
const app = express();
// Enable CORS for all routes
app.use(cors());
// Or configure specific origins
app.use(cors({
origin: ['http://localhost:3000', 'http://localhost:5173'], // React, Vite defaults
credentials: true, // Allow cookies
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
app.get('/api/users', (req, res) => {
res.json({ users: ['John', 'Jane'] });
});
app.listen(8000, () => {
console.log('API server running on port 8000');
});
Install the cors package first:
npm install cors
Explanation
CORS errors occur when your browser blocks requests from one domain (frontend) to another (API server). The cors()
middleware adds the necessary headers (Access-Control-Allow-Origin
, etc.) to your responses.
Using cors()
without options allows all origins. For production, specify exact origins in the origin
array. Set credentials: true
if you need to send cookies or authorization headers with requests.
Share this article
Add Comment
No comments yet. Be the first to comment!