HTTP module in Node.js is used to create HTTP server and transfer data over it. Using HTTP module you can create a web server over Hyper Text Transfer protocol – HTTP to accepts request and response accordingly.
To start using it, use require('http')
method like below:
const http = require('http');
Creating a Server using HTTP module:
Using createServer() method we can create a simple HTTP server in node.js.
The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.
Use the createServer()
method to create an HTTP server:
myServer.js:
http.createServer((request, response) => { //my first Node.js web server using http response.write('My first Node.js web server using http'); response.end(); }).listen(3000); //the server will run on port 3000
This will create and start a local server on port no 3000
and you can run it by using command node myServer.js
on terminal window.
We can set the response header by using method setHeader:
response.setHeader('Content-Type', 'application/json');
Reading Query Strings:
For reading query strings passed in the URL address, we need to use another built-in module named 'url'
.
myServer.js:
const http = require('http'); const url = require('url'); http.createServer((request, response) => { var queries = url.parse(request.url, true).query; console.log(queries); response.write("You passed Color:" + queries.color + ", Number:" + queries.number + ", Place:" + queries.place); response.end(); }).listen(3000);
console.log(‘Server started on port no. 3000’);
Now run this by running command node myServer.js
on terminal window. On a browser window open url:
localhost:3000/?number=7&place=Mumbai&color=black