JAVASCRIPT
Configuring CORS Preflight for Express API
Learn to properly configure Cross-Origin Resource Sharing (CORS) preflight requests in a Node.js Express API, enabling secure cross-domain client-side communication.
const express = require('express');
const cors = require('cors'); // npm install cors
const app = express();
const port = 3000;
// Basic CORS configuration for simple requests (GET, POST, HEAD with allowed headers)
// For more complex needs (e.g., custom headers, PUT/DELETE methods), preflight is triggered.
// app.use(cors());
// Advanced CORS configuration for handling preflight requests for specific origins/methods
const allowedOrigins = ['http://localhost:8080', 'https://your-frontend-domain.com'];
const corsOptions = {
origin: function (origin, callback) {
// Allow requests with no origin (like mobile apps or curl requests)
// or if the origin is in our allowed list.
if (!origin || allowedOrigins.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // Explicitly allow methods
allowedHeaders: ['Content-Type', 'Authorization', 'X-Custom-Header'], // Explicitly allow headers
credentials: true, // Allow cookies to be sent with requests
optionsSuccessStatus: 200 // Some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.use(cors(corsOptions));
// Middleware to parse JSON body
app.use(express.json());
// A simple GET route
app.get('/api/data', (req, res) => {
res.json({ message: 'Hello from the API!', timestamp: new Date() });
});
// A route that requires a PUT method and custom header, triggering a preflight
app.put('/api/resource/:id', (req, res) => {
const customHeader = req.headers['x-custom-header'];
res.json({
message: `Resource ${req.params.id} updated!`,
data: req.body,
'x-custom-header-received': customHeader
});
});
app.listen(port, () => {
console.log(`API server listening at http://localhost:${port}`);
console.log('Test with a frontend from http://localhost:8080');
console.log('Example: fetch(\'http://localhost:3000/api/resource/123\', { method: \'PUT\', headers: { \'Content-Type\': \'application/json\', \'X-Custom-Header\': \'Value\' }, body: JSON.stringify({ name: \'Test\' }) })');
});
How it works: This Node.js Express snippet demonstrates how to configure CORS (Cross-Origin Resource Sharing) middleware, specifically handling preflight `OPTIONS` requests. When a browser detects a "complex" cross-origin request (e.g., using `PUT`/`DELETE` methods, or custom headers), it first sends an `OPTIONS` request (the preflight) to check if the actual request is safe to send. The `cors` package allows defining `origin`, `methods`, and `allowedHeaders` to inform the browser which requests are permitted, ensuring secure cross-domain communication between your frontend and API.