0
0
Node.jsframework~5 mins

Status code usage patterns in Node.js

Choose your learning style9 modes available
Introduction

Status codes tell the browser or client what happened with a request. They help show if things worked or if there was a problem.

When sending a response after a user submits a form.
When an API returns data or an error.
When redirecting a user to another page.
When a requested page or resource is not found.
When the server has an error and cannot complete the request.
Syntax
Node.js
res.status(code).send(body)

code is a number like 200, 404, or 500.

res is the response object in Node.js frameworks like Express.

Examples
Sends a success message with status code 200.
Node.js
res.status(200).send('OK')
Sends a message that the page or resource was not found.
Node.js
res.status(404).send('Not Found')
Sends a message that something went wrong on the server.
Node.js
res.status(500).send('Server Error')
Sample Program

This simple Express server shows three routes. Each route sends a different status code and message to explain what happened.

Node.js
import express from 'express';
const app = express();

app.get('/success', (req, res) => {
  res.status(200).send('Request succeeded');
});

app.get('/notfound', (req, res) => {
  res.status(404).send('Page not found');
});

app.get('/error', (req, res) => {
  res.status(500).send('Internal server error');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always use the correct status code to help clients understand the response.

Common codes: 200 (OK), 201 (Created), 400 (Bad Request), 401 (Unauthorized), 404 (Not Found), 500 (Server Error).

Use res.status() before sending the response body.

Summary

Status codes tell the client what happened with the request.

Use res.status(code) to set the status code in Node.js.

Pick the right code to make your app clear and easy to debug.