Response Handling

Tutorial 4 of 4

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!