0
0
Expressframework~10 mins

Status code conventions in Express - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Status code conventions
Client sends HTTP request
Server processes request
Determine response status code
Send response with status code
Client receives response and acts accordingly
This flow shows how a server using Express decides and sends HTTP status codes back to the client after processing a request.
Execution Sample
Express
app.get('/user', (req, res) => {
  if (!req.query.id) {
    res.status(400).send('Bad Request');
  } else {
    res.status(200).send('User found');
  }
});
This Express route sends a 400 status if no user ID is given, otherwise sends 200.
Execution Table
StepCondition CheckedStatus Code SetResponse SentExplanation
1Is req.query.id present?NoNoCheck if user ID is missing
2req.query.id missing400'Bad Request'Send 400 Bad Request because ID is missing
3Is req.query.id present?YesNoUser ID is present, proceed
4req.query.id present200'User found'Send 200 OK with user found message
💡 Response sent with appropriate status code based on presence of user ID
Variable Tracker
VariableStartAfter Step 1After Step 3Final
req.query.idundefined or valueundefined or valuevalue if presentvalue if present
res.statusCodeunset400 if missing200 if present400 or 200 depending on condition
Key Moments - 2 Insights
Why do we use different status codes like 400 and 200?
Because 400 means the client sent a bad request (missing ID), while 200 means the request was successful. See execution_table rows 2 and 4.
What happens if we forget to set a status code?
Express defaults to 200 OK if no status is set. So the client might think the request succeeded even if it didn't.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what status code is sent when req.query.id is missing?
A404
B400
C200
D500
💡 Hint
Check row 2 in the execution_table where req.query.id is missing
At which step does the server send a 200 status code?
AStep 3
BStep 2
CStep 4
DStep 1
💡 Hint
Look at the execution_table row where status code 200 is set
If we remove res.status(400), what status code will Express send when ID is missing?
A200
B400
C404
D500
💡 Hint
Recall Express defaults to 200 if no status is set (see key_moments answer 2)
Concept Snapshot
Status codes tell the client how the request went.
400 means bad request (client error).
200 means success.
Use res.status(code) before sending response.
Always send correct status for clarity.
Full Transcript
In Express, when a client sends a request, the server checks conditions like if required data is present. Based on that, it sets a status code using res.status(code). For example, if a user ID is missing, the server sends 400 Bad Request. If the ID is present, it sends 200 OK. This helps the client understand if the request succeeded or failed. If no status is set, Express defaults to 200. So always set the right status code before sending a response.