0
0
Node.jsframework~15 mins

Setting response headers in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Setting Response Headers in Node.js
📖 Scenario: You are building a simple web server using Node.js. You want to send back a response with custom headers to tell the browser how to handle the content.
🎯 Goal: Create a Node.js server that responds to requests with a custom Content-Type header and a X-Custom-Header header.
📋 What You'll Learn
Create a basic HTTP server using Node.js http module
Set the Content-Type header to text/plain
Set a custom header called X-Custom-Header with the value MyHeaderValue
Send a simple text response body
💡 Why This Matters
🌍 Real World
Web servers often need to send headers to control how browsers handle content, such as content type, caching, or security policies.
💼 Career
Understanding how to set response headers is essential for backend developers working with Node.js to build APIs and web servers.
Progress0 / 4 steps
1
Create a basic HTTP server
Write code to import the http module and create a server variable called server using http.createServer().
Node.js
Need a hint?

Use require('http') to import the module and http.createServer() to create the server.

2
Add a request listener function
Add a request listener function to server that takes req and res as parameters.
Node.js
Need a hint?

Pass a function with req and res parameters to http.createServer().

3
Set response headers
Inside the request listener, use res.setHeader() to set the Content-Type header to text/plain and the X-Custom-Header to MyHeaderValue.
Node.js
Need a hint?

Use res.setHeader(name, value) to add headers before sending the response.

4
Send the response and listen on port 3000
Inside the request listener, use res.end() to send the text Hello, world!. Then call server.listen(3000) to start the server on port 3000.
Node.js
Need a hint?

Use res.end() to finish the response and server.listen(3000) to start listening.