Node.js has built-in HTTP module to transfer data over http protocol. HTTP module also used to create http server and send response to the specific server port.
To use the HTTP module, use require() method to import module.
const http = require('http');
Now use createServer()
method to create HTTP server and listen() method listen to the given port.
Here is the example. Create file http.js and save the below code into it.
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer(function(req, res) {
res.write('Hello World!\n');
res.end();
});
server.listen(port, hostname, function() {
console.log(`Server running at http://${hostname}:${port}/`);
});
Now run the file into node from Terminal.
node http.js
You will see below console message into response.
Open the browser and input url http://127.0.0.1:3000/
. The server will response the data that we passed in res.write()
method.
You can also send response header using res.writeHead()
method. The below example will return 'Content-Type': 'text/html'
header in response.
const http = require('http');
const server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>Hello World!</h1>');
res.end();
}).listen(3000);
In this article, we have learned to create http server and send response data with header. In the next article, we will use other methods of http module.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Confirmation alert Before Delete record using jQuery Ajax, PHP and MySQL
While creating web application, it is al...How to create a PHP package for Composer
PHP has become more popular programing l...JQuery add or remove class using addClass, removeClass and toggleClass methods
Sometimes you need to change diplay prop...Laravel 5.5 - simple crud operation with example
Today, we are sharing how to make s...Share Data Between Child and Parent Components in Angular 12 Part 2
In the previous article, we have created...