0
0
Expressframework~5 mins

Preflight requests behavior in Express

Choose your learning style9 modes available
Introduction

Preflight requests check if a web server allows certain actions from a browser before sending the real request. This helps keep your app safe.

When your web app needs to send data with methods like PUT or DELETE.
When your app sends custom headers with requests.
When your app requests resources from a different domain (cross-origin).
When you want to control which websites can talk to your server.
When debugging CORS issues in your Express backend.
Syntax
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.

Examples
This example responds to preflight requests on '/api/data' by allowing certain methods and headers.
Express
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);
});
This middleware sets CORS headers for all requests, helping preflight requests pass.
Express
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();
});
Sample Program

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.

Express
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');
});
OutputSuccess
Important Notes

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.

Summary

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.