Performance: Preflight requests behavior
Preflight requests add extra network round-trips before the main request, impacting page load speed and interaction responsiveness.
const cors = require('cors'); const corsOptions = { origin: 'https://example.com', methods: ['GET', 'POST'], allowedHeaders: ['Content-Type'], optionsSuccessStatus: 204 }; app.use(cors(corsOptions));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
return res.status(204).json({});
}
next();
});| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Generic CORS middleware allowing all origins and methods | N/A | N/A | Adds network delay before DOM can render | [X] Bad |
| Specific CORS middleware with limited origins, methods, and headers | N/A | N/A | Minimal network delay, faster content rendering | [OK] Good |
app.options('/data', (req, res) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,POST');
res.sendStatus(204);
});
What will the server respond to an OPTIONS request to '/data'?app.options('/api', (req, res) => {
res.header('Access-Control-Allow-Origin', 'https://example.com');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT');
res.end();
});
But the browser still blocks the actual request. What is the likely problem?Pass the test and this pattern moves unknown