0
0
Expressframework~30 mins

Conditional requests handling in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Conditional Requests Handling in Express
📖 Scenario: You are building a simple Express server that serves a static message. To optimize bandwidth and improve performance, you want to handle conditional requests using the If-None-Match header with ETags.This means the server will respond with 304 Not Modified if the client's cached version is still valid, avoiding sending the full response again.
🎯 Goal: Create an Express server that serves a message at /message with an ETag header. The server should check the If-None-Match header from the client and respond with 304 Not Modified if the ETag matches, or send the message with the ETag if it does not.
📋 What You'll Learn
Create an Express app with a route /message
Define a constant ETag string etagValue with value "12345"
Check the If-None-Match header from the request
Respond with 304 status if the ETag matches
Otherwise, respond with status 200, the message body, and set the ETag header
💡 Why This Matters
🌍 Real World
Conditional requests handling is used in web servers to reduce data transfer by letting clients cache resources and only download updates when needed.
💼 Career
Understanding how to implement ETag and conditional requests is important for backend developers to optimize API performance and improve user experience.
Progress0 / 4 steps
1
Setup Express app and route
Create an Express app by requiring express and calling express(). Then create a GET route handler for /message that sends the text 'Hello, world!' with status 200.
Express
Need a hint?

Use require('express') to import Express. Then call express() to create the app. Use app.get('/message', (req, res) => { ... }) to define the route.

2
Add ETag constant
Add a constant variable called etagValue and set it to the string "12345" above the route handler.
Express
Need a hint?

Use const etagValue = "12345"; to define the ETag string.

3
Check If-None-Match header and respond conditionally
Inside the /message route handler, get the If-None-Match header from req.headers. If it equals etagValue, respond with status 304 and end the response. Otherwise, continue to send the message with status 200 and set the ETag header to etagValue.
Express
Need a hint?

Use req.headers['if-none-match'] to get the header. Compare it to etagValue. If equal, send 304 with res.status(304).end(). Otherwise, set the ETag header and send the message.

4
Start the server on port 3000
Add code to start the Express server listening on port 3000 using app.listen. Log the message 'Server running on port 3000' when the server starts.
Express
Need a hint?

Use app.listen(3000, () => { console.log('Server running on port 3000'); }) to start the server.