How to edit response information in Express.js

I will show you how to modify the response information in Express.js. I will also post the code on Git Hub, so please refer to it.

overview

In Express.js, you handle requests inside middleware functions. A request object and a response object are passed as arguments to the middleware function. You use these objects to retrieve data related to requests, generate responses, and so on.

Here, we will explain how to modify the response information in Express.js using the following versions:

Express.js v4.17.1
Node.js v16.3.0

In addition, all the code created this time is posted on GitHub.

How to edit response information

A response object is used to construct the response to the client. Used in Express route handlers to set response headers, status codes, data, etc.

The sample code below is an example for understanding the response object (response object) in Express.js. It takes GET requests and generates and returns different kinds of responses.

response.js

const express = require('express');
const app = express();

app.get("/json", (req, res) => {
  // Generate JSON response
  const jsonResponse = {
    message: "This is a JSON response",
  };
  res.json(jsonResponse);
});

app.get("/html", (req, res) => {
  // Generate HTML response
  const htmlResponse = "<h1>This is an HTML response</h1>";
  res.type("text/html").send(htmlResponse);
});

app.get("/header", (req, res) => {
  // setting response headers
  res.setHeader("Custom-Header", "Custom Value");
  res.send("Header set");
});

app.get("/status", (req, res) => {
  // set status code
  res.status(201).send("Created");
});

app.get("/redirect", (req, res) => {
  // perform redirect
  res.redirect("/new-location");
});

app.get("/error", (req, res) => {
  // Generate error response
  const errorResponse = {
    error: "An error occurred",
  };
  res.status(500).json(errorResponse);
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Commentary

  • Importing Express modules
const express = require('express');
const app = express();

The above code loads the module named express to create a new Express application.

  • the root of the JSON response
app.get("/json", (req, res) => {
  const jsonResponse = {
    message: "This is a JSON response",
  };
  res.json(jsonResponse);
});

If a GET request is sent to the “/json” endpoint, this code will return a JSON formatted response.

  • HTML response root
app.get("/html", (req, res) => {
  const htmlResponse = "<h1>This is an HTML response</h1>";
  res.type("text/html").send(htmlResponse);
});

If a GET request is sent to the “/html” endpoint, this code will return an HTML formatted response.

  • Root for setting response headers
app.get("/header", (req, res) => {
  res.setHeader("Custom-Header", "Custom Value");
  res.send("Header set");
});

If a GET request is sent to the “/header” endpoint, this code will add custom headers to the response headers and return the result as the response.

  • root of status code setting
app.get("/status", (req, res) => {
  res.status(201).send("Created");
});

If a GET request is sent to the “/status” endpoint, this code will set the response status code to 201 (Created) and return the result as the response.

  • redirect route
app.get("/redirect", (req, res) => {
  res.redirect("/new-location");
});

If a GET request is sent to the “/redirect” endpoint, this code will redirect and redirect the user to a new URL ("/new-location").

  • error response route
app.get("/error", (req, res) => {
  const errorResponse = {
    error: "An error occurred",
  };
  res.status(500).json(errorResponse);
});

If a GET request is sent to the “/error” endpoint, this code sets the response status code to 500 (Internal ServerError) and returns a JSON-formatted response containing the error message.

  • Start server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

This code will start the server on port 3000. If the server starts successfully, you should see the message ‘Server is running on port 3000’ on the console.

test

## An endpoint that returns a JSON response
curl -X GET http://localhost:3000/json
## An endpoint that returns an HTML response
curl -X GET http://localhost:3000/html
## An endpoint to add custom headers to the response
curl -X GET http://localhost:3000/header
## endpoints returning a specific status code
curl -X GET http://localhost:3000/status
## An endpoint that returns an error response
curl -X GET http://localhost:3000/error

In this code I am generating different kinds of responses inside the route handler. Features include JSON responses, HTML responses, custom headers, status codes, redirects, error responses, and more. Concise and flexible response generation is possible using Express convenience methods.

summary

By using response objects (res objects), you can:

  • You can set or change response headers.
  • You can set the HTTP status code of the response.
  • You can set the body data of the response. It can return data in the form of JSON objects, strings, binary data, etc.
  • You can set response encoding and compression.
  • It is possible to control responses according to specific situations, such as redirects and error handling.

Response objects allow you to perform various operations related to response generation within your Express application. Response objects have many properties and methods that allow for a high degree of customization and control.