Understanding the http requests in Node

Node.jsServer Side ProgrammingProgramming

App.js

const http = require('http');
const server = http.createServer((req, res)=>{
   console.log(req);
});
server.listen(3000);

Run it with command: node App.js

We can see what is inside a request object by opening a browser and navigating to localhost:3000

There is lots of information which will get printed on console window. We will see some important properties.

Identifying the url from where request came, request method type and headers in request is important.

Headers will give us information on host and browser type , accepted response by host etc. Request method can be of any http method type like GET, POST, PUT, DELETE etc.

const http = require('http');
const server = http.createServer((req, res)=>{
   console.log(req.url, req.method, req. headers);
});
server.listen(3000);

in above screenshot, we are printing request url , method and headers information. Information on console will be shown below −

The request url we can is /hello. Request method type is GET and headers information which shows host accepts response of type text/html etc. It also contains which http version is used by checking logs .

Request url is helpful to route it to correct controller in node. Request method is helpful for identifying url parameters and fetching data from request. Post http methods contains the data in body while GET method will be having data in url parameters. Type of response which requires to send will be identified from headers accept property.

Node provides this useful information from request object.

So far, we are working on request from browser. But there will be scenarios where we will require executing a request from node file itself. This can be achieved by installing a module called request

npm install request

const request = require("request");
request(" your url here ", function(error, response, body) {
   console.log(‘data’, body);
});

There are multiple ways of doing a request. We can use Axios library as well. Axios is another popular library to make http calls.

npm install axios@0.16.2
const axios = require('axios');
axios.get(' your url here’)
.then(responseObject => {
   console.log(responseObject.data.url);
   console.log(responseObject.data.explanation);
})
.catch(error => {
   console.log(error);
});

There are many other libraries too, which can used as per your comfort.

raja
Published on 13-May-2020 14:58:50
Advertisements