0
0
Expressframework~30 mins

Preflight requests behavior in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling Preflight Requests in Express
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use app.get('/', (req, res) => { res.send('Hello World') }) and export the app.