CORS Mini Project — Build a Cross-Origin API with Express
In this tutorial, you will learn about CORS Mini Project. We cover key concepts, practical examples, and best practices to help you master this topic.
Build a complete CORS-enabled Express API with a React frontend to demonstrate how cross-origin requests work, including preflight handling, credential support, and security restrictions.
What You'll Learn
- Implementing CORS in a real Express server
- Testing cross-origin requests from a React frontend
- Debugging and fixing CORS issues
Why It Matters
This project simulates a real-world scenario: a frontend app on one origin communicating with a backend API on another origin.
flowchart LR
A["React App\nhttp://localhost:3000"] -->|"fetch()"| B["Express API\nhttp://localhost:5000"]
B --> C["CORS Middleware\nConfigures headers"]
C --> D["API Route Handlers"]
D -->|"Response + CORS headers"| A
style B fill:#dbeafe,stroke:#2563eb
Project Structure
cors-project/
server/
package.json
index.js
client/
package.json
src/App.js
Server Code
// server/index.js
const express = require('express');
const cors = require('cors');
const app = express();
const allowedOrigins = ['http://localhost:3000'];
app.use(cors({
origin: (origin, callback) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Origin not allowed'));
}
},
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type'],
credentials: true
}));
app.get('/api/data', (req, res) => {
res.json({ message: 'CORS works!', timestamp: Date.now() });
});
app.listen(5000, () => console.log('API on :5000'));
Client Code
// client/src/App.js
import { useState, useEffect } from 'react';
function App() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('http://localhost:5000/api/data', {
credentials: 'include'
})
.then(res => res.json())
.then(setData)
.catch(err => console.error('CORS test failed:', err));
}, []);
return (
<div>
<h1>CORS Test</h1>
{data ? <pre>{JSON.stringify(data, null, 2)}</pre> : 'Loading...'}
</div>
);
}
Testing
# Start server
node server/index.js
# In another terminal, start React client
cd client && npm start
# Test CORS directly
curl -I http://localhost:5000/api/data \
-H "Origin: http://localhost:3000"
Common Mistakes
1. Running Server and Client on Same Port
They must be on different ports (or origins) to test CORS.
2. Not Allowing the Correct Origin
The origin check in CORS middleware must match precisely including port.
3. Forgetting Credentials in Both Sides
credentials: 'include' on the client and credentials: true on the server.
4. Using Different Protocols
Mixing http://localhost:3000 and https://localhost:5000 creates different origins.
5. Not Watching the Network Tab
The browser Network tab shows exactly which CORS headers are exchanged.
FAQ
What's Next
Your CORS knowledge is complete. Explore HATEOAS for hypermedia-driven APIs or API Authentication for securing your endpoints.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro