📖 Scenario: You are building a simple Node.js server that responds to client requests with appropriate HTTP status codes.This helps clients understand if their request was successful or if there was an error.
🎯 Goal: Create a Node.js server using the http module that sends different status codes based on the request URL.You will practice setting status codes like 200, 404, and 500 correctly.
📋 What You'll Learn
Create a basic HTTP server using Node.js http module
Add a variable to hold the success status code 200
Use an if-else statement to send status code 200 for the root URL and 404 for unknown URLs
Add a final else block to send status code 500 for server errors
💡 Why This Matters
🌍 Real World
Web servers must send correct HTTP status codes so browsers and clients know how to handle responses.
💼 Career
Understanding status codes is essential for backend developers and anyone working with web APIs or servers.
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 respond with status code 200 and the text 'Hello World' for any request.
Node.js
Hint
Use http.createServer and set res.statusCode = 200 inside the callback.
2
Add a status code variable
Add a variable called successCode and set it to 200. Use this variable to set the response status code instead of the number directly.
Node.js
Hint
Create const successCode = 200; before the server and use it in res.statusCode.
3
Send 200 for root and 404 for others
Inside the server callback, use if (req.url === '/') to send status code successCode with 'Hello World'. Use else to send status code 404 with 'Not Found'.
Node.js
Hint
Use if (req.url === '/') to check the URL and set status codes accordingly.
4
Add 500 status code for errors
Update the logic: change the existing else to else if (req.url === '/notfound') to send status code 404 and 'Not Found' for that specific URL. Then add a final else block to send status code 500 and 'Server Error' for all other cases. This simulates distinguishing specific client errors from server errors.
Node.js
Hint
Change the existing else to else if (req.url === '/notfound') and add a new else block for status code 500.
Practice
(1/5)
1. What does the HTTP status code 200 generally indicate in a Node.js response?
easy
A. The client made a bad request with invalid syntax.
B. The request was successful and the server returned the requested data.
C. The requested resource was not found on the server.
D. The server encountered an internal error.
Solution
Step 1: Understand HTTP status codes
HTTP status codes communicate the result of a client's request to the server.
Step 2: Identify the meaning of 200
Status code 200 means the request succeeded and the server sent back the expected data.
Final Answer:
The request was successful and the server returned the requested data. -> Option B
Quick Check:
200 = Success [OK]
Hint: 200 means success, data sent back properly [OK]
Common Mistakes:
Confusing 200 with error codes like 400 or 500
Thinking 200 means resource not found
Mixing up client and server error codes
2. Which of the following is the correct way to set a 404 status code in a Node.js Express response?
easy
A. res.status(404).send('Not Found');
B. res.sendStatus(404, 'Not Found');
C. res.code(404).send('Not Found');
D. res.setStatus(404).send('Not Found');
Solution
Step 1: Recall Express response methods
Express uses res.status(code) to set status codes before sending a response.
Step 2: Check method correctness
res.status(404).send('Not Found'); correctly sets status 404 and sends the message.
Final Answer:
res.status(404).send('Not Found'); -> Option A
Quick Check:
Use res.status(code) to set status [OK]
Hint: Use res.status(code) before sending response [OK]
Common Mistakes:
Using non-existent methods like res.code or res.setStatus
Passing status code as second argument to send
Confusing sendStatus with status
3. Consider this Express code snippet:
app.get('/data', (req, res) => {
if (!req.query.id) {
return res.status(400).send('Missing id');
}
res.status(200).send('Data for ' + req.query.id);
});
What status code will the server respond with if the client calls /data without an id query parameter?
medium
A. 400
B. 404
C. 200
D. 500
Solution
Step 1: Analyze the condition for missing id
The code checks if req.query.id is missing and returns status 400 with message 'Missing id'.
Step 2: Determine response when id is missing
If id is absent, the server responds immediately with status 400 (bad request).
Final Answer:
400 -> Option A
Quick Check:
Missing required data = 400 [OK]
Hint: Missing required input usually means 400 Bad Request [OK]
C. The res.status(201) should come before the if block.
D. It sends two responses if name is missing, causing an error.
Solution
Step 1: Check response flow when name is missing
If !req.body.name is true, res.sendStatus(422) sends a response but code continues.
Step 2: Identify double response issue
After sending 422, the code still calls res.status(201).send('Created'), causing an error because response was already sent.
Final Answer:
It sends two responses if name is missing, causing an error. -> Option D
Quick Check:
Send response once per request [OK]
Hint: Return after sending response to avoid double sends [OK]
Common Mistakes:
Not returning after sending a response
Confusing 422 with invalid status code
Thinking order of status calls matters without return
5. You want to create an Express route that returns a JSON error with status 403 if the user is not authorized, and status 200 with data if authorized. Which code snippet correctly implements this pattern?
hard
A. app.get('/secret', (req, res) => {
if (!req.user) {
res.status(403).json({ error: 'Forbidden' });
}
res.status(200).json({ data: 'Secret info' });
});
B. app.get('/secret', (req, res) => {
if (!req.user) {
res.sendStatus(403);
} else {
res.sendStatus(200).json({ data: 'Secret info' });
}
});