Express.js / Handling Requests and Responses

Sending JSON and HTML Responses

This tutorial focuses on sending JSON and HTML responses in Express. You will learn how to send responses in various formats based on the client's request.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explores working with request and response objects in Express.

1. Introduction

In this tutorial, you'll learn how to send JSON and HTML responses using Express, a popular web application framework for Node.js. Express makes it easy to send different types of responses to the client, depending on the request.

By the end of the tutorial, you will be able to:
- Understand how to send JSON responses
- Learn how to send HTML responses
- Make use of Express's res.json and res.send methods

Prerequisites: Basic understanding of Node.js, Express, and JavaScript.

2. Step-by-Step Guide

Express provides several ways to send responses to a client. The most commonly used methods are res.send and res.json. Both methods can send responses but are used for different content types.

res.send method

The res.send function sends a response to the client and automatically sets the content type based on the response. If you send an object or array, Express will send it as JSON.

Example:

app.get('/send', (req, res) => {
  res.send('Hello World!')
})

res.json method

The res.json function also sends a response to the client but always sends the response as JSON.

Example:

app.get('/json', (req, res) => {
  res.json({ message: 'Hello World!' })
})

3. Code Examples

Here are some practical examples:

Example 1: Sending a JSON response

// Import express
const express = require('express')

// Initialize express
const app = express()

app.get('/json', (req, res) => {
  // Sending JSON response
  res.json({ message: 'Hello, this is a JSON response!' })
})

app.listen(3000, () => console.log('Server started on port 3000'))

Example 2: Sending an HTML response

// Import express
const express = require('express')

// Initialize express
const app = express()

app.get('/html', (req, res) => {
  // Sending HTML response
  res.send('<h1>Hello, this is an HTML response!</h1>')
})

app.listen(3000, () => console.log('Server started on port 3000'))

4. Summary

In this tutorial, you've learned how to send both JSON and HTML responses using Express. You've practiced using the res.json and res.send functions to send different types of responses.

To continue learning about Express, check out the official Express documentation.

5. Practice Exercises

Exercise 1: Write an Express route that responds with a JSON object containing your name and age.

Solution:

app.get('/me', (req, res) => {
  res.json({ name: 'Your Name', age: 'Your Age' })
})

Exercise 2: Write an Express route that responds with an HTML page containing a headline and a paragraph.

Solution:

app.get('/page', (req, res) => {
  res.send('<h1>Welcome to my page</h1><p>This is a paragraph.</p>')
})

Use these exercises to practice sending different types of responses. Remember, the best way to learn coding is by doing!

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

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Time Zone Converter

Convert time between different time zones.

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