RESTful APIs / Building RESTful APIs with Node.js and Express

Response Handling

In this tutorial, you will learn how to handle responses in Express. This will include how to structure your response, set response status, and send back appropriate data.

Tutorial 4 of 4 4 resources in this section

Section overview

4 resources

Explains how to build REST APIs using Node.js and Express framework.

1. Introduction

In this tutorial, we aim to understand how to handle responses in Express, a flexible Node.js web application framework. You will learn how to structure your response, set response status, and send back appropriate data to the client.

By the end of this tutorial, you will be able to:

  • Understand how responses work in Express
  • Set response status codes
  • Send JSON, HTML, or any other type of response
  • Handle errors in responses

Before starting, it's recommended that you have a basic understanding of JavaScript and Node.js. Familiarity with Express would be beneficial but is not required.

2. Step-by-Step Guide

Responses in Express are instances of the Response object. This object has many methods to send HTTP responses. The most commonly used methods are res.send, res.json, and res.status.

res.send and res.json

Both res.send and res.json are used to send a response body. However, res.json also converts non-object values into JSON.

app.get('/', function(req, res) {
  res.send('Hello World')
})

In this example, the res.send method sends a response of "Hello World" to the HTTP request.

res.status

The res.status method is used to set the HTTP status code of the response.

app.get('/', function(req, res) {
  res.status(404).send('Not found')
})

Here, we're sending a 404 status code with a message of "Not found".

3. Code Examples

Let's look at some examples to better understand response handling in Express.

Sending a JSON response

app.get('/user', function(req, res) {
  res.json({ name: 'John', age: 30 })
})

In this example, we are sending a JSON response containing user data.

Sending a status code and JSON response

app.get('/error', function(req, res) {
  res.status(500).json({ error: 'Something went wrong' })
})

Here, we are sending a 500 (Internal Server Error) status code along with a JSON response that includes an error message.

4. Summary

In this tutorial, you've learned how to handle responses in Express, including how to set status codes and send various types of responses. To further expand your knowledge, you may want to investigate other response methods available in Express, such as res.render for rendering view templates, or res.redirect for redirecting to a different URL.

5. Practice Exercises

  1. Create an Express route that sends a 400 status code and a JSON response with an error message.
  2. Create an Express route that sends a JSON response with a list of products.
  3. Create an Express route that sends a 404 status code with a custom "Not found" message.

Here's a hint for the first exercise:

app.get('/bad-request', function(req, res) {
  // Your code here
})

For more practice, try to create your own Express application and experiment with different types of responses. Good luck!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

File Size Checker

Check the size of uploaded files.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help