Preflight requests check if a web server allows certain actions from a browser before sending the real request. This helps keep your app safe.
Preflight requests behavior in Express
app.options(path, middleware, handler)
app.options handles HTTP OPTIONS requests, which are used for preflight checks.
You can add middleware to set headers like Access-Control-Allow-Origin here.
app.options('/api/data', (req, res) => { res.set('Access-Control-Allow-Origin', '*'); res.set('Access-Control-Allow-Methods', 'GET,POST,PUT'); res.set('Access-Control-Allow-Headers', 'Content-Type'); res.sendStatus(204); });
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});This Express app sets CORS headers for all requests. It specifically handles OPTIONS requests to '/data' by allowing GET, POST, and PUT methods. When a browser sends a preflight request, the server replies with allowed methods and headers. The PUT route responds with a simple message.
import express from 'express'; const app = express(); // Middleware to handle CORS headers app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); }); // Handle preflight OPTIONS request app.options('/data', (req, res) => { res.header('Access-Control-Allow-Methods', 'GET,POST,PUT'); res.sendStatus(204); // No Content }); // Actual route app.put('/data', (req, res) => { res.send('Data updated'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Preflight requests use the HTTP OPTIONS method before the actual request.
Always respond to OPTIONS requests quickly with status 204 (No Content) to avoid delays.
Setting Access-Control-Allow-Origin to '*' allows all websites to access your API, which may not be safe for sensitive data.
Preflight requests check permissions before sending real requests.
Express handles preflight with app.options() for OPTIONS method.
Set proper CORS headers to allow or restrict cross-origin requests.