HTTP in Node.JS

Create a basic web server with the HTTP module

The Web

Websites don’t use a command-line terminal to serve web pages. A basic server can be made in just a few lines of code:

server.js

1.   const http = require('http');
2. 
3.   const host = '127.0.0.1';
4.   const port = 34321;
5. 
6.   const server = http.createServer((request, response) => {
7.     response.statusCode = 200;
8.     response.setHeader('Content-Type', 'text/html');
9.     response.end('Welcome to Node.JS');
10.  });
11.
12.  server.listen(port, host, () => {
13.    console.log(`Server running at http://${host}:${port}`);
14.  });

Code Explanation

  • The http module is imported on line 1.

  • The host and port for the server are declared on lines 3 and 4.

  • The createServer method on line 6 creates a new http.Server instance. A requestListener is an optional function used as a callback. The request event is automatically fired when a client requests something from the server.

  • The request is an instance of the http.IncomingMessage class and the response is an instances of the HTTP.ServerResponse class.

  • The statusCode property set method on line 7 sets the HTTP status code. We set it to 200, which indicates success. A list of the HTTP status codes with meanings can be found here.

  • HTTP headers allow the client and server to pass additional information with an HTTP request or response. We change the Content-Type header and set it to text/html on line 8. Details on HTTP headers can be found here.

  • The end method tells the server that the headers and body have been sent. This method must be called on each response. On line 9 we invoke the end method, passing "Welcome to Node.JS" as our data.

Production web servers are considerably more complex than the one above. This serves as a simple example of how to create a basic web server.

Reference:

Node.JS HTTP Module