Bytes

Handling Incoming Requests and Sending Responses

Importing the HTTP Module

To create an HTTP server in Node.js, we need to import the built-in HTTP module. The HTTP module provides essential functionality for creating an HTTP server, including handling incoming requests and sending responses. To import the module, we simply use the require() function like so:

const http = require('http');

Once we have imported the HTTP module, we can use its methods to handle incoming requests and send responses.

Handling Incoming Requests

When a client makes a request to our server, it sends a request object to our server. This object contains information about the incoming request, such as the URL, headers, and body. In order to handle incoming requests, we need to read and parse this incoming request data.

Reading and Parsing Incoming Request Data

To read and parse the incoming request data, we can use the data and end events of the request object. The data event is emitted whenever the request object receives data, and the end event is emitted when the entire request has been received.

Here is an example of how we can read and parse incoming request data:

const server = http.createServer((req, res) => {
  let body = '';
  req.on('data', (chunk) => {
    body += chunk.toString();
  });
  req.on('end', () => {
    console.log(`Received request with data: ${body}`);
  });
});

In this example, we listen to the data event of the req object and concatenate the received data chunks into a single string. Once the entire request has been received (end event), we can then parse the request data and perform the necessary actions.

Handling Different HTTP Methods

HTTP defines several methods for interacting with resources on the web, including GET, POST, PUT, and DELETE. To handle these different HTTP methods, we can use a switch statement on the req.method property.

Here is an example of how we can handle different HTTP methods:

const server = http.createServer((req, res) => {
  switch (req.method) {
    case 'GET':
      // Handle GET request
      break;
    case 'POST':
      // Handle POST request
      break;
    case 'PUT':
      // Handle PUT request
      break;
    case 'DELETE':
      // Handle DELETE request
      break;
    default:
      res.statusCode = 405;
      res.end();
      break;
  }
});

In this example, we use a switch statement to handle different HTTP methods. If the request method is not one of the expected methods, we set the response status code to 405 (Method Not Allowed) and end the response.

Sending Responses

Once we have processed the incoming request, we need to send a response back to the client. To do this, we set the response status code, write response headers, and write the response body.

Setting Response Status Codes and Status Messages

HTTP status codes are three-digit numbers that indicate the status of the response. They provide information about whether the request was successful, redirected, or encountered an error. To set the response status code and message, we can use the res.statusCode and res.statusMessage properties, respectively.

Here is an example of how we can set the response status code and message:

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.statusMessage = 'OK';
// Send response
});

In this example, we set the response status code to 200 (OK) and the response status message to 'OK'.

Writing Response Headers and Body

HTTP responses also include headers, which provide additional information about the response. To write response headers, we can use the res.setHeader() method. This method takes two arguments: the header name and the header value.

Here is an example of how we can write response headers:

const server = http.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  // Send response
});

In this example, we set the Content-Type header to text/html.

To write the response body, we can use the res.write() method. This method takes a string or a buffer as an argument.

Here is an example of how we can write the response body:

const server = http.createServer((req, res) => {
  res.write('Hello, World!');
  // Send response
});

In this example, we write the string 'Hello, World!' to the response body.

To end the response, we can use the res.end() method. This method takes an optional argument that specifies the last data to be sent.

Here is an example of how we can end the response:

const server = http.createServer((req, res) => {
  res.write('Hello, World!');
  res.end();
});

In this example, we end the response after writing the string 'Hello, World!' to the response body.

Ending the Response Process with response.end()

When we are done writing the response headers and body, we need to end the response process to send the response to the client. To do this, we can use the response.end() method. The response.end() method signals to the server that all the response headers and body have been sent to the client.

Here is an example of how we can end the response process using response.end():

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello World!');
  res.end();
});

server.listen(3000, () => {
  console.log('Server running at <http://localhost:3000/>');
});

In this example, we are creating an HTTP server that listens to incoming requests on port 3000. When a request is received, we are writing a response header with a status code of 200 and content type of text/plain. We are then writing a response body with the text Hello World!. Finally, we are ending the response process with response.end().

Example: Echo Server That Returns the Received Request Data

An echo server is a simple HTTP server that receives a request and returns the same request data to the client. The server simply echoes back the request data to the client. This can be useful in testing network connectivity or validating that the client and server are communicating properly.

Here is an example of how we can create an echo server that returns the received request data:

const http = require('http');

const server = http.createServer((req, res) => {
  let data = '';
  req.on('data', chunk => {
    data += chunk;
  });
  req.on('end', () => {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(data);
  });
});

server.listen(3000, () => {
  console.log('Echo server listening on port 3000');
});

In this example, we are creating an HTTP server that listens to incoming requests on port 3000. When a request is received, we are reading the request data using the data event and concatenating the received chunks into a single string. When the entire request has been received, we are setting the response header with a status code of 200 and content type of text/plain. We are then sending back the received request data in the response body using response.end(data).

Conclusion

In conclusion, building an HTTP server in Node.js is a powerful way to handle incoming requests and send responses to clients. We can handle different HTTP methods, set response status codes and status messages, write response headers and body, and end the response process with response.end(). We can also create custom servers like the echo server that can be used for testing or validation purposes. By understanding these concepts, we can build efficient and robust HTTP servers that can handle a wide range of client requests.

Module 5: Building an HTTP ServerHandling Incoming Requests and Sending Responses

Top Tutorials

Related Articles

AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter