0
0
Node.jsframework~10 mins

Response methods and status codes in Node.js - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Response methods and status codes
Receive HTTP Request
Choose Response Method
Set Status Code
Send Response Body
Client Receives Response
The server receives a request, selects a response method, sets a status code, sends the response, and the client receives it.
Execution Sample
Node.js
res.status(404).send('Not Found');
Sets the HTTP status to 404 and sends 'Not Found' as the response body.
Execution Table
StepActionStatus CodeResponse BodyResult
1Call res.status(404)404undefinedStatus code set to 404
2Call res.send('Not Found')404'Not Found'Response sent with status 404 and body
3Client receives response404'Not Found'Client sees 404 status and message
4End404'Not Found'Response cycle complete
💡 Response sent, cycle ends
Variable Tracker
VariableStartAfter Step 1After Step 2Final
statusCode200 (default)404404404
responseBodyundefinedundefined'Not Found''Not Found'
Key Moments - 2 Insights
Why do we chain res.status(404).send('Not Found') instead of calling them separately?
Because res.status sets the status code and returns the response object, allowing send to immediately send the response with that status. See execution_table steps 1 and 2.
What happens if we call res.send() without setting a status code first?
The response uses the default status code 200 (OK). This is shown in variable_tracker where statusCode starts at 200.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the status code after step 1?
A500
B404
C200
DUndefined
💡 Hint
Check the 'Status Code' column at step 1 in execution_table
At which step is the response body set to 'Not Found'?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Response Body' column in execution_table
If we omit res.status(404) and only call res.send('OK'), what status code will the client receive?
A200
B404
C500
DUndefined
💡 Hint
Refer to variable_tracker where statusCode starts at 200 by default
Concept Snapshot
res.status(code) sets HTTP status code
res.send(body) sends response body
Chain methods: res.status(404).send('Not Found')
Default status is 200 if not set
Client receives status and body together
Full Transcript
In Node.js, when handling HTTP requests, you use response methods to send data back to the client. First, you can set the status code with res.status(code). This changes the HTTP status like 404 for Not Found or 200 for OK. Then, you send the response body with res.send(body). These methods can be chained so that res.status(404).send('Not Found') sets the status and sends the message in one go. If you don't set a status, it defaults to 200. The client receives both the status code and the response body together. This flow ensures clear communication about the result of the request.