Making HTTP requests with Node.js
In this tutorial, we will learn how to make HTTP Requests and different HTTP methods.
There are quite many options available to make a request which we’ll cover throughout this tutorial.
Some Popular HTTP Methods are:
Request.GET
Request.POST
Request.PUT
Request.DELETE
An HTTP request is passing a configuration object or just the URL to the request() the method along with a callback function. The Request Module is the most Popular Node package for making HTTP Requests. Here HTTP stands for Hypertext Transfer Protocol and is used to structure requests and responses. It transfers data from one point to another over the network.
See the Below Example:
const https = require('https'); https.get('https://json.typicode.com/user', res => { let data = []; const headerDate = res.headers && res.headers.date ? res.headers.date : 'no response date'; console.log('Status Code:', res.statusCode); console.log('Date in Response header:', headerDate); res.on('data', chunk => { data.push(chunk); }); res.on('end', () => { console.log('Response ended: '); const users = JSON.parse(Buffer.concat(data).toString()); for(user of users) { console.log(`Got user with id: ${user.id}, name: ${user.name}`); } }); }).on('error', err => { console.log('Error: ', err.message); });
If data has been requested, the server will respond by sending the data to the client and also it will always send a status code denoting success or failure.HTTP Request is a message from the client to the server. It is called an HTTP message because we are going to send a message through a protocol that means a client and server communicate in a protocol called HTTP protocol.
In the world of the web, there is hyperlink means documents are connected in the form of hyperlinks clicking one hyperlink leads to another document.
Important Configuration that we can include in the object are:
1. URL-The destination URL of the request.
2. Method-The HTTP methods like GET, POST, PUT, and DELETE.
3. Header: HTTP header as an object of key-value pair
If a user clicks on "Show all the books" <a href="http://localhost:400/categories/02/books"> Show all the books </a> The HTTP message is sent from client to server, The HTTP Request message sent is: GET/categories/books HTTP/1.1 Host:localhost:3600 User-Agent: Google Chrome/4.0(Compatible; Windows NT) .URL-/categories/02/books Request Method use is GET it symbolizes that I need to get that particular resource.
Some Shorthand Methods: request.get(options, callback) request.post(options, callback) request.head(options, callback) request.delete(options, callback)
Thanks for Reading hope yOU like this blog.
HAPPY CODING !!!
Leave a Reply