0
0
Node.jsframework~30 mins

Response methods and status codes in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Response Methods and Status Codes in Node.js
📖 Scenario: You are building a simple web server using Node.js that responds to client requests with different messages and status codes.This is like a shopkeeper who greets customers differently depending on their request and tells them if something is okay or if there is a problem.
🎯 Goal: Create a Node.js server that uses response methods to send messages and status codes to the client.You will learn how to set status codes and send text responses properly.
📋 What You'll Learn
Create a basic HTTP server using Node.js
Use res.statusCode to set HTTP status codes
Use res.end() to send responses
Send different messages for different URL paths
Use correct status codes for success and error
💡 Why This Matters
🌍 Real World
Web servers use status codes and response methods to tell browsers if a page loaded successfully or if there was an error.
💼 Career
Understanding how to send correct status codes and responses is essential for backend developers working with Node.js and building APIs.
Progress0 / 4 steps
1
Create a basic HTTP server
Create a Node.js HTTP server using http.createServer and assign it to a variable called server. The server should listen on port 3000.
Node.js
Need a hint?

Use const server = http.createServer((req, res) => { }) to create the server.

Then call server.listen(3000) to start it.

2
Set status code for root URL
Inside the server callback, add an if statement to check if req.url is '/'. If yes, set res.statusCode to 200.
Node.js
Need a hint?

Use if (req.url === '/') to check the URL.

Set res.statusCode = 200 inside the block.

3
Send response message for root URL
Inside the if block for req.url === '/', send the text response 'Welcome to the homepage!' using res.end().
Node.js
Need a hint?

Use res.end('Welcome to the homepage!') to send the message and end the response.

4
Handle unknown URLs with 404 status
Add an else block after the if for req.url === '/'. Inside it, set res.statusCode to 404 and send the response 'Page not found' using res.end().
Node.js
Need a hint?

Use else after the if block.

Inside else, set res.statusCode = 404 and call res.end('Page not found').