Sending JSON and HTML Responses

Tutorial 4 of 5

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!