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