0
0
Expressframework~15 mins

req.headers for HTTP headers in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Accessing HTTP Headers with req.headers in Express
📖 Scenario: You are building a simple Express server that needs to read HTTP headers sent by clients. HTTP headers carry important information like user agents or custom tokens.
🎯 Goal: Create an Express server that reads the req.headers object to access HTTP headers and sends back a response showing one specific header value.
📋 What You'll Learn
Create an Express app with a single GET route at '/'
Use req.headers to access the HTTP headers object
Extract the user-agent header from req.headers
Send a response that includes the user-agent header value
💡 Why This Matters
🌍 Real World
Web servers often need to read HTTP headers to understand client details, like browser type or authentication tokens.
💼 Career
Knowing how to access HTTP headers with req.headers is essential for backend developers working with Express to handle requests properly.
Progress0 / 4 steps
1
Set up Express app and import express
Write code to import express and create an Express app instance called app.
Express
Need a hint?

Use require('express') to import Express and call it to create app.

2
Create a GET route at '/'
Add a GET route handler on app for path '/' with parameters req and res.
Express
Need a hint?

Use app.get with path '/' and a callback with req and res.

3
Access the user-agent header from req.headers
Inside the GET route, create a variable called userAgent and set it to req.headers['user-agent'] to get the user agent string.
Express
Need a hint?

Use bracket notation req.headers['user-agent'] to get the header value.

4
Send the user-agent header value in the response
Use res.send to send a string response that says User Agent: followed by the userAgent variable.
Express
Need a hint?

Use template strings with backticks to include userAgent in the response.