How to edit response information in Node.js

Introduces how to modify response information in Node.js. The code is also posted on Git Hub, so please refer to it.

overview

Node.js creates an HTTP server and handles requests. Here, we will explain how to modify the response information in Node.js using the following versions:

Node.js v16.3.0

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

How to edit response information

We will use the Node.js http module to create an HTTP server and manipulate the response.

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

response.js

const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
  const path = url.parse(req.url, true).pathname;

  switch(path) {
    case "/json":
      const jsonResponse = {
        message: "This is a JSON response",
      };
      res.writeHead(200, {'Content-Type': 'application/json'});
      res.end(JSON.stringify(jsonResponse));
      break;

    case "/html":
      const htmlResponse = "<h1>This is an HTML response</h1>";
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.end(htmlResponse);
      break;

    case "/header":
      res.setHeader("Custom-Header", "Custom Value");
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end("Header set");
      break;

    case "/status":
      res.writeHead(201, {'Content-Type': 'text/plain'});
      res.end("Created");
      break;

    case "/error":
      const errorResponse = {
        error: "An error occurred",
      };
      res.writeHead(500, {'Content-Type': 'application/json'});
      res.end(JSON.stringify(errorResponse));
      break;

    default:
      res.writeHead(404, {'Content-Type': 'text/plain'});
      res.end("Not Found");
  }
});

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

Commentary

  • Importing Node.js modules
const http = require('http');
const url = require('url');

The code above loads Node.js modules named http and url.

  • the root of the JSON response
case "/json":
  const jsonResponse = {
    message: "This is a JSON response",
  };
  res.writeHead(200, {'Content-Type': 'application/json'});
  res.end(JSON.stringify(jsonResponse));
  break;

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

  • HTML response root
case "/html":
  const htmlResponse = "<h1>This is an HTML response</h1>";
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end(htmlResponse);
  break;

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

  • Root for setting response headers
case "/header":
  res.setHeader("Custom-Header", "Custom Value");
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end("Header set");
  break;

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
case "/status":
  res.writeHead(201, {'Content-Type': 'text/plain'});
  res.end("Created");
  break;

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.

  • error response route
case "/error":
  const errorResponse = {
    error: "An error occurred",
  };
  res.writeHead(500, {'Content-Type': 'application/json'});
  res.end(JSON.stringify(errorResponse));
  break;

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
server.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. It shows features such as JSON responses, HTML responses, custom headers, status codes, redirects, error responses

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.