0
I am building a React frontend that connects to a Node.js Express backend hosted on a separate domain. Simple GET requests work fine, but POST and PUT requests fail with a CORS error during the preflight phase. How should OPTIONS requests be handled correctly on the server?
Express CORS Configuration
Preflight requests use the HTTP OPTIONS method. Here is how to configure Express to return proper CORS headers.
const express = require('express');
const app = express();
// Handle CORS preflight explicitly
app.use((req, res, next) => {
// Allow requests from frontend domain
res.header('Access-Control-Allow-Origin', 'https://app.example.com');
// Specify allowed headers
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
// Specify allowed HTTP methods
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
// Intercept preflight OPTIONS request
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
});Debugging Checklist
- Verify that response headers match the exact origin instead of wildcards when using credentials
- Check if reverse proxies (like Nginx) strip CORS headers
- Ensure status code 200 or 204 is returned for OPTIONS requests