0
0
Expressframework~15 mins

res.set for response headers in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Setting Response Headers with res.set in Express
📖 Scenario: You are building a simple Express server that sends back a greeting message. To make your response more informative and secure, you want to add custom HTTP headers.
🎯 Goal: Learn how to use res.set in Express to add custom response headers before sending the response.
📋 What You'll Learn
Create an Express app with a single GET route at '/'
Use res.set to add a custom header 'X-Custom-Header' with value 'HelloHeader'
Add another header 'Content-Type' with value 'text/plain'
Send a plain text response 'Welcome to the header demo!'
💡 Why This Matters
🌍 Real World
Web servers often need to send custom headers for security, caching, or metadata. Using <code>res.set</code> in Express helps control these headers easily.
💼 Career
Backend developers use Express to build APIs and web servers. Knowing how to set response headers is essential for controlling client-server communication.
Progress0 / 4 steps
1
Create the Express app and basic route
Create a variable called express that requires the 'express' module. Then create a variable called app by calling express(). Finally, add a GET route at path '/' with a callback function that takes req and res as parameters.
Express
Need a hint?

Use require('express') to import Express and express() to create the app. Use app.get to define the route.

2
Add custom headers using res.set
Inside the GET route callback, use res.set to add a header 'X-Custom-Header' with value 'HelloHeader'. Also add a header 'Content-Type' with value 'text/plain'.
Express
Need a hint?

Call res.set twice with the exact header names and values.

3
Send the plain text response
After setting the headers, use res.send to send the text 'Welcome to the header demo!' as the response body.
Express
Need a hint?

Use res.send with the exact string to send the response.

4
Start the Express server
Add a line to start the server by calling app.listen on port 3000 with a callback function that logs 'Server running on port 3000'.
Express
Need a hint?

Use app.listen with port 3000 and a callback that logs the message.