English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer & URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

NodeJS Other

Node.js Create HTTP Server

In this tutorial, we will learn how to create an HTTP Web server using http in Node.js. The HTTP built-in module'screateServer()Methods.

Creating an HTTP Web Server in Node.js

Node.js provides a built-in module HTTP, which is stable and compatible with the NPM ecosystem.

The following is a step-by-step tutorial on how to create an HTTP Web server in Node.js:

Steps1: Include HTTP module

Create a .js file named httpWebServer.js and open it in a text editor.

Include the built-in Node.js module HTTP using the require function, as shown below.

// Include the http module in the file
var http = require('http'); 
 
// Create a server
http.createServer(function (req, res) { 
    // HTTP headers
    // 200-Confirm message
    // To respond with HTML content, 'Content-Type” should be “text / html"
    res.writeHead(200, {'Content-Type': 'text/html'});  
    res.write('Node.js says hello!'); //Write response to the client
    res.end(); //End of Response
 }).listen(9000); //The server object at port9000

Steps4: Run Web Server

Run the httpWebServer.js file (from the previous step) to create the server and make the server listen on port9000.

 $ node httpWebServer.js

The server will start and run.

Steps5: Test Web Server

Open the browser and click on the URL 'http://127.0.0.1:9000/”, to trigger a request to our web server.

Look! We have created an HTTP Web server that listens on port number9000 port and respond with a text message in HTML format 'Hello from Node.js!' for any request.

This may not be the complete web server you expect for your project, but it is undoubtedly the first step in building an HTTP Web Server.

Conclusion:

In this Node.js tutorial–Creating an HTTP Web server in Node.js, we used http. HTTP is an in-built module of Node.js.createServer()Method to create an HTTP Web server to respond to requests made on the port.