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]
How to create Helpers function in Laravel 8
Laravel ships with rich global function...Laravel Blade If Condition Example
Laravel blade template provides directiv...Laravel 8 CRUD operation tutorial for beginners
When you start learning any programming,...Laravel Excel Import Export with Example.
In this article, we will discuss La...How To Install phpMyAdmin on Ubuntu 20.04
phpMyadmin is open-source web applicatio...