📖 Scenario: You are building a simple Express server that needs to handle cross-origin requests from a frontend app. Browsers send a preflight request using the HTTP OPTIONS method to check if the server allows the actual request.To make your server work correctly with cross-origin requests, you need to handle these preflight requests properly.
🎯 Goal: Create an Express server that responds correctly to preflight OPTIONS requests by sending the right CORS headers and status code.
📋 What You'll Learn
Create an Express app instance
Set a variable allowedOrigin with the value 'http://example.com'
Add middleware to handle OPTIONS requests for all routes
Respond to OPTIONS requests with status 204 and the correct CORS headers
💡 Why This Matters
🌍 Real World
Handling preflight requests is essential for APIs that serve frontend apps running in browsers, ensuring smooth cross-origin communication.
💼 Career
Understanding and implementing CORS and preflight request handling is a common task for backend developers working with web APIs.
Progress0 / 4 steps
1
Create the Express app
Create a variable called express that requires the 'express' module. Then create a variable called app by calling express().
Express
Hint
Use require('express') to import Express and then call it to create the app.
2
Set the allowed origin variable
Create a constant variable called allowedOrigin and set it to the string 'http://example.com'.
Express
Hint
Use const allowedOrigin = 'http://example.com' to set the allowed origin.
3
Add middleware to handle OPTIONS preflight requests
Add middleware to app that listens for all OPTIONS requests on any path using app.options('*', ...). Inside the handler function, set the response headers Access-Control-Allow-Origin to allowedOrigin, Access-Control-Allow-Methods to 'GET,POST,PUT,DELETE', and Access-Control-Allow-Headers to 'Content-Type'. Then send a response with status code 204 and no content.
Express
Hint
Use app.options('*', (req, res) => { ... }) to handle all OPTIONS requests.
4
Complete the server with a simple GET route
Add a GET route on / that responds with the text 'Hello World'. Then export the app module using module.exports = app.
Express
Hint
Use app.get('/', (req, res) => { res.send('Hello World') }) and export the app.
Practice
(1/5)
1. What is the main purpose of a preflight request in Express when handling cross-origin requests?
easy
A. To check if the server allows the actual request method and headers before sending it
B. To send the actual data to the server immediately
C. To close the connection after the first request
D. To authenticate the user credentials
Solution
Step 1: Understand preflight request role
A preflight request uses the OPTIONS method to ask the server if the actual request is safe to send.
Step 2: Identify what preflight checks
It checks allowed methods and headers to prevent unauthorized cross-origin requests.
Final Answer:
To check if the server allows the actual request method and headers before sending it -> Option A
Quick Check:
Preflight checks permissions = B [OK]
Hint: Preflight = permission check before real request [OK]
Common Mistakes:
Thinking preflight sends actual data
Confusing preflight with authentication
Assuming preflight closes connection
2. Which Express method is used to handle preflight OPTIONS requests?
easy
A. app.options()
B. app.post()
C. app.get()
D. app.use()
Solution
Step 1: Recall HTTP methods in Express
Express provides methods matching HTTP verbs like get, post, options, etc.
Step 2: Identify method for preflight
Preflight requests use the OPTIONS method, so Express uses app.options() to handle them.
Final Answer:
app.options() -> Option A
Quick Check:
OPTIONS method handled by app.options() [OK]
Hint: Preflight uses OPTIONS, so use app.options() [OK]
Common Mistakes:
Using app.get() or app.post() for OPTIONS requests
Confusing app.use() as handler for OPTIONS
Not handling OPTIONS method at all
3. Consider this Express code snippet handling CORS preflight:
But the browser still blocks the actual request. What is the likely problem?
medium
A. Access-Control-Allow-Origin should be '*'
B. Using res.end() instead of res.sendStatus(204)
C. Missing Access-Control-Allow-Headers header for custom headers
D. Incorrect URL path in app.options()
Solution
Step 1: Understand preflight header requirements
If the actual request uses custom headers, the server must respond with Access-Control-Allow-Headers listing them.
Step 2: Check code for missing headers
The code does not set Access-Control-Allow-Headers, so browser blocks the request due to missing allowed headers.
Final Answer:
Missing Access-Control-Allow-Headers header for custom headers -> Option C
Quick Check:
Missing allowed headers header blocks request = D [OK]
Hint: Always include Access-Control-Allow-Headers if custom headers used [OK]
Common Mistakes:
Assuming res.end() causes the block
Thinking Access-Control-Allow-Origin must be '*' always
Ignoring missing allowed headers header
5. You want to allow cross-origin requests only from 'https://trusted.com' with methods GET and POST, and allow custom header 'X-Custom-Auth'. Which Express preflight handler is correct?