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]
Neumorphism/Soft UI CSS shadow generator
There are lots of softwares available fr...Upload Single and Multiple Images with Preview in React with Example
Today in this React image upload preview...How to remove white space from the end of a string in PHP
Use the PHP rtrim() function...How to check if a variable exists or defined in JavaScript
Use the typeof operator If...Django 3 CRUD Tutorial Example with MySQL and Bootstrap
Django 3 is released with full async sup...