0
0
Node.jsframework~5 mins

Response methods and status codes in Node.js

Choose your learning style9 modes available
Introduction

Response methods and status codes help your server tell the browser what happened with a request. They make communication clear and organized.

When sending data back to a user after they ask for a webpage or API info.
When telling the browser if something went wrong, like a missing page or server error.
When confirming that a form submission was successful.
When redirecting a user to another page.
When sending different types of content like JSON, HTML, or files.
Syntax
Node.js
res.status(code).send(body)
res.status(code).json(object)
res.send(body)
res.json(object)
res.redirect(url)

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

status(code) sets the HTTP status code before sending the response.

Examples
Sends a plain text response with status 200 (success).
Node.js
res.status(200).send('OK')
Sends a 404 status with a message when a page is missing.
Node.js
res.status(404).send('Page not found')
Sends a JSON response with default status 200.
Node.js
res.json({ message: 'Hello' })
Redirects the user to the login page.
Node.js
res.redirect('/login')
Sample Program

This simple Express server shows different response methods and status codes:

  • Root path sends a 200 status with text.
  • /data sends JSON data with default 200 status.
  • /notfound sends a 404 status with a message.
  • /redirect sends a redirect to the homepage.
Node.js
import express from 'express';
const app = express();

app.get('/', (req, res) => {
  res.status(200).send('Welcome to the homepage!');
});

app.get('/data', (req, res) => {
  res.json({ name: 'Alice', age: 30 });
});

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

app.get('/redirect', (req, res) => {
  res.redirect('/');
});

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

Always set the status code before sending the response.

Use res.json() to send JSON data easily.

Common status codes: 200 (OK), 404 (Not Found), 500 (Server Error), 302 (Redirect).

Summary

Response methods send data and status codes tell the browser what happened.

Use res.status(code) to set status before sending.

Common methods: send(), json(), and redirect().