0
0
Expressframework~10 mins

res.status for status codes in Express - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - res.status for status codes
Request received
Set status code with res.status(code)
Attach response data (optional)
Send response with res.send() or res.json()
Client receives response with status code
This flow shows how Express sets HTTP status codes using res.status, then sends the response to the client.
Execution Sample
Express
app.get('/example', (req, res) => {
  res.status(404).send('Not Found');
});
This code sets the HTTP status to 404 and sends a 'Not Found' message to the client.
Execution Table
StepActionres.status CodeResponse BodyEffect
1Request to /example received200undefinedServer prepares to respond
2Call res.status(404)404undefinedStatus code set to 404
3Call res.send('Not Found')404'Not Found'Response sent with status 404 and body
4Client receives response404'Not Found'Client sees 404 status and message
💡 Response sent; Express ends request-response cycle
Variable Tracker
VariableStartAfter Step 2After Step 3Final
res.statusCode200404404404
res.bodyundefinedundefined'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(code) sets the status and returns the res object, allowing chaining. The execution_table row 2 shows status set, and row 3 shows send called on the same res.
What happens if we call res.send() without res.status()?
Express defaults status to 200 OK. The execution_table shows status is 200 before res.status, meaning default 200 is used if not set.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the status code after step 2?
Aundefined
B404
C200
D500
💡 Hint
Check the 'res.status Code' column at step 2 in the execution_table
At which step is the response body set to 'Not Found'?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Response Body' column in the execution_table
If we remove res.status(404), what status code will the client receive?
A500
B404
C200
D302
💡 Hint
Refer to key_moments answer about default status code when res.status is not called
Concept Snapshot
res.status(code) sets HTTP status code for the response
It returns res to allow chaining like res.status(404).send('msg')
If not set, status defaults to 200 OK
Use res.send() or res.json() to send response body
Always set status before sending response
Full Transcript
In Express, when a request comes in, you can set the HTTP status code using res.status(code). This sets the status code for the response. Then you send the response body using res.send() or res.json(). The status code defaults to 200 if you don't set it. The res.status method returns the res object so you can chain calls like res.status(404).send('Not Found'). This flow ensures the client receives the correct status and message.