An in-depth look at the five methods of making HTTP requests in Node.js

Translation: crazy no English title: 5 Ways to Make HTTP Requests in the Node. Js the original link: www.twilio.com/blog/2017/0…

Creating HTTP requests is one of the core functions of modern programming languages, and one of the first techniques many programmers encounter when they approach a new development environment. There are a number of solutions available in Node.js, including language built-in functionality and development libraries contributed by the open source community. Let’s take a look at some of the more popular ones.

In the case of this article, we will use the “Daily Space Photos API” provided by NASA as the JSON API for interaction, because space is the coolest thing ever.

Before you start, install the latest version of Node.js and NPM on your computer.

HTTP – Standard library

The first is the default HTTP module in the standard library. This module does not need to be installed to rely on external use, achieve true plug and play. The downside is that it is less user-friendly than other solutions.

The following code will send a GET request to NASA’s API and output the URL of the astronomical photo of the day, along with its annotations:

const https = require('https');
 
https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
  let data = ' ';
 
  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });
 
  // The whole response has been received. Print out the result.
  resp.on('end', () = > {console.log(JSON.parse(data).explanation);
  });
 
}).on("error", (err) => {
  console.log("Error: " + err.message);
});
Copy the code

Most of the functionality provided by the HTTP and HTTPS modules is fairly limited. Instead of just providing a callback function, you need to receive the response data on a block basis so that you can execute it as soon as all the data is received. If it’s in JSON format you’ll have to parse it manually. Although it is not a lot of work, it still introduces some unnecessary operations.

Another problem is that THE HTTP and HTTPS protocols are separate modules, so if the API we use is communicating over HTTPS, we need HTTPS modules.

If you don’t want to add too many dependencies to your code base or want to use its underlying functionality, it may take more effort to get the data you need, but it’s still a good tool.

Request

Request is a simplified HTTP client that is similar to Python’s Request library. This library is better to use than the default HTTP module and has been the development preference of the open source community for years.

I’ve been using Node.js since I started, and it’s great for getting things done quickly. Unlike the HTTP module, you must install it using NPM.

From terminal, go to the directory where you want the code to be downloaded and run the following command:

NPM install [email protected]Copy the code

As you can see, you don’t need to write too much code to accomplish the previous functions:

const request = require('request');
 
request('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', { json: true }, (err, res, body) => {
  if (err) { return console.log(err); }
  console.log(body.url);
  console.log(body.explanation);
});
Copy the code

If you want the pain of handling HTTP requests in the normal way, Request is a good choice. If you want to make Promises, you can also check out the Request-Promise library.

Axios

Axios is a Promise-based HTTP client that can be used in browsers and Node.js. Using Promises has great advantages when dealing with code that requires a more complex chain of events. Writing asynchronous code can be confusing, and Promises is one of several solutions to that problem. They are even used in other languages, such as Swift.

Using NPM to install Axios, enter the following command in the terminal:

NPM install [email protected]Copy the code

The code below does the same thing, getting the URL and interpreting the astronomy picture for the day.

const axios = require('axios');
 
axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY')
  .then(response= > {
    console.log(response.data.url);
    console.log(response.data.explanation);
  })
  .catch(error= > {
    console.log(error);
  });
Copy the code

By default, Axios can parse JSON responses, which is very convenient. You can also see that error handling is done by.catch(), now we’re all using Promises.

You can even make multiple concurrent requests via axios.all, for example if you want to get two days of astronomical images at once:

var axios = require('axios');
 
axios.all([
  axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=2017-08-03'),
  axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=2017-08-02')
]).then(axios.spread((response1, response2) = > {
  console.log(response1.data.url);
  console.log(response2.data.url);
})).catch(error= > {
  console.log(error);
});
Copy the code

Asynchronous code can easily become very complex and difficult to deal with, and the way it solves this problem may make your life easier in the long run. Axios solves this problem very easily and will make your development life easier in the long run.

SuperAgent

Similar to Axios, SuperAgent is another popular library, mostly for Ajax requests in browsers, but also for Node.js. Run the following command to install the SuperAgent:

NPM install [email protected]Copy the code

The cool thing about SuperAgent is that it can make chained calls. You can chain other functions to requests like Query () and add arguments. In the previous examples we added them manually. Note how the SuperAgent provides this functionality:

const superagent = require('superagent');
 
superagent.get('https://api.nasa.gov/planetary/apod')
.query({ api_key: 'DEMO_KEY'.date: '2017-08-02' })
.end((err, res) = > {
  if (err) { return console.log(err); }
  console.log(res.body.url);
  console.log(res.body.explanation);
});
Copy the code

Like Axios, you don’t have to parse the JSON response yourself, which is pretty cool.

Got

Got is another option if you want to use a more lightweight library. It is also available for Twilio Functions.

NPM install Got

NPM install [email protected]Copy the code

Got, like Axios, works well with Promises. The following code does the same thing as the previous example:

const got = require('got');
 
got('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', { json: true }).then(response= > {
  console.log(response.body.url);
  console.log(response.body.explanation);
}).catch(error= > {
  console.log(error.response.body);
});
Copy the code

If you want a lightweight library that isn’t as bloated as Request, use Got.

Final thoughts

This isn’t the complete solution, but you get an idea of how the basic functionality of some popular HTTP libraries in Node.js works. There are also libraries such as Node-Fetch that port the fetch functionality of the browser to the back end. There are various similar libraries to address this problem in other languages, such as Python and Ruby.

The original article was first published on the official account: Jingcheng Yideng

The original address: mp.weixin.qq.com/s/pDhS4G8U7…