nodejs
  1. nodejs-http

Node.js HTTP

Node.js provides the built-in "http" module that allows you to create the HTTP server and make HTTP requests. In this tutorial, we will discuss how to use the http module in Node.js.

Syntax

The syntax for creating an HTTP server in Node.js using the http module is as follows:

const http = require('http');

const server = http.createServer((req, res) => {
  // handle request
});

server.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

The createServer() method returns an instance of an HTTP server.

Example

Let's say we want to create an HTTP server that returns "Hello, World!" to all incoming requests. Here's how we can implement it:

const http = require('http');

const port = 3000;

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

server.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

Now, we can run the server using the following command:

node server.js

When we visit http://localhost:3000 in our web browser, we will see the message "Hello, World!".

Output

When we run the example code above and visit the server in our web browser, we will see the message "Hello, World!".

Explanation

In the example above, we imported the http module and created an HTTP server instance using the createServer() method. We passed a callback function to createServer() that will be executed whenever there's an incoming request.

The callback function takes two arguments: req (the request object) and res (the response object). We then set the status code of the response to 200, set the content type to plain text, and write the message "Hello, World!" to the response.

We then told the server to listen to incoming requests on port 3000.

Use

The http module is used for creating an HTTP server that listens to incoming requests and for handling HTTP requests.

Important Points

  • When creating an HTTP server, you must specify a callback function that will handle incoming requests.
  • The request object (req) contains information about the incoming request, such as the URL, request headers, and request method.
  • The response object (res) is used for sending the response back to the client and contains methods for setting the status code, headers, and response data.

Summary

In this tutorial, we discussed how to use the http module for creating an HTTP server in Node.js. We covered the syntax, example, output, explanation, use, and important points of the http module. With this knowledge, you can create HTTP servers using Node.js to handle incoming requests and responses.

Published on: