Understanding CORS in Node.js
Cross-Origin Resource Sharing (CORS) is a browser mechanism that allows or restricts web pages from making requests to a domain different from the one that served the web page. It is crucial for securing APIs and enabling controlled cross-origin requests.
Why CORS is Needed
- Restricts unauthorized domains from accessing your API
- Enables secure integration between front-end and back-end
- Respects browser security policies for data privacy
Enabling CORS in Node.js
Step 1: Install the CORS Package
npm install cors
Step 2: Basic Usage
// server.js
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/api/data', (req, res) => {
res.json({ message: 'CORS-enabled endpoint' });
});
app.listen(5000, () => {
console.log('Server running on http://localhost:5000');
});
Custom CORS Options
const corsOptions = {
origin: 'http://localhost:3000',
methods: ['GET', 'POST'],
credentials: true
};
app.use(cors(corsOptions));
HTML Client Example
You can test the CORS-enabled API with a simple HTML page like this:
<!DOCTYPE html>
<html>
<head>
<title>CORS Test</title>
</head>
<body style="font-family: Prompt, sans-serif;">
<h3>Fetch Data</h3>
<button onclick="fetchData()">Fetch</button>
<pre id="output"></pre>
<script>
function fetchData() {
fetch('http://localhost:5000/api/data')
.then(res => res.json())
.then(data => {
document.getElementById('output').textContent = JSON.stringify(data, null, 2);
})
.catch(error => {
document.getElementById('output').textContent = 'Error: ' + error;
});
}
</script>
</body>
</html>
Conclusion
CORS is a necessary configuration for secure communication between frontend and backend when operating across different origins. Use permissive settings during development, but always lock it down in production environments.