Status Codes

HTTP status codes tell the client how the request went.

Syntaxres.statusCode = 404;

Every HTTP response carries a status code describing the outcome. They are grouped by their first digit:

RangeMeaningExample
2xxSuccess200 OK, 201 Created
3xxRedirect301 Moved, 304 Not Modified
4xxClient error400 Bad Request, 404 Not Found
5xxServer error500 Internal Error

Example

Example Β· javascript
const http = require('http');

const server = http.createServer((req, res) => {
  if (req.method !== 'GET') {
    res.writeHead(405); // Method Not Allowed
    return res.end('Only GET is allowed');
  }
  res.writeHead(200);
  res.end('OK');
});

server.listen(3000);

When to use it

  • A REST API returns `422 Unprocessable Entity` when a request body passes JSON parsing but fails business-logic validation.
  • An authentication service returns `401 Unauthorized` when a token is missing and `403 Forbidden` when the token is valid but the user lacks the required role.
  • A redirect middleware returns `301 Moved Permanently` to upgrade legacy HTTP URLs to HTTPS so browsers and search engines update their links.

More examples

Common status codes in responses

Returns 200, 403, and 404 status codes for different routes -- the most common HTTP status codes in a REST API.

Example Β· js
const http = require('http');

http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('OK');
  } else if (req.url === '/secret') {
    res.writeHead(403);
    res.end('Forbidden');
  } else {
    res.writeHead(404);
    res.end('Not Found');
  }
}).listen(3000);

Redirect with 301

Issues a 301 permanent redirect by setting the `Location` header -- browsers will follow it automatically.

Example Β· js
const http = require('http');

http.createServer((req, res) => {
  if (req.url === '/old-path') {
    res.writeHead(301, { Location: '/new-path' });
    return res.end();
  }
  res.writeHead(200);
  res.end('New path content');
}).listen(3000);

Return 201 after creating a resource

Returns 201 Created for a successful POST and 405 Method Not Allowed for any other method on that route.

Example Β· js
const http = require('http');

http.createServer((req, res) => {
  if (req.method === 'POST' && req.url === '/users') {
    // ... create user ...
    res.writeHead(201, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ id: 99, created: true }));
  } else {
    res.writeHead(405);
    res.end('Method Not Allowed');
  }
}).listen(3000);

Discussion

  • Be the first to comment on this lesson.
Status Codes β€” Node.js | SoundsCode