Node.js learning Note 6 - network request and API call

Posted by live_ex3me on Fri, 07 Feb 2020 06:44:22 +0100

Network requests and API calls

It will take about 10 minutes to read this blog

Network programming is a very important part of web development. JS, as the closest part of web development, is very powerful in network programming. Then Node ecology also provides various convenient tools to send and receive network requests.

Our most basic tool is the Request module, and then the third party also provides Promise based tools, such as Axios, node fetch, etc.

  • Request
  • axios
  • node-fetch

Resources for developers, by developers.

introduce

Let's use a few small examples to experience the following differences in coding:

  1. Request
  2. Web RESTful API
  3. axios
  4. node-fetch

Request

  1. introduce
    Request is a super simple HTTP Client tool.
    Its goal is to send http requests in the simplest way.

To install the Request module:

npm install request --save
  1. Basic usage:
var req = require('request');

req('http://www.bing.com', function(error, response, body){
    if (!error && response.statusCode == 200) {
        console.log(body) // Show the HTML for the baidu homepage.
      }
});

Request transmits data asynchronously through callback. Now there are many other more powerful tools to help complete the work.

Web RESTful API

  1. RESTful

rest is the abbreviation of three words of REpresentational State Transfer, which was proposed by Roy Fielding in 2000. It represents the architecture style of distributed services.

  1. Demo API:

Next, use the sample api to demo applications:

https://reqres.in/api/users

Query the data of a user:

https://reqres.in/api/users/1

Return result:

{
    "data": {
        "id": 1,
        "email": "george.bluth@reqres.in",
        "first_name": "George",
        "last_name": "Bluth",
        "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"
    }
}

Suppose we need to query the basic data through the user id first, and then get the user's head image according to the url saved in the avatar field.

Let's see how to do this with axios and node fetch.

axios

  1. introduce
    The famous Promise based HTTP Client in Node.js is easy to use and efficient.
    The main features include support for Promise, automatic conversion of JSON data, support for interceptors, and rich configuration items. At present, it is widely used.

To install the axios module:

npm install axios --save
  1. Through aysnc/await

axios_demo.js:

const axios = require('axios');
const fs = require('fs');
const url = 'https://reqres.in/api/users';

const getPicByUser = async user => {

    try {
        const userResponse = await axios.get(url + '/' + user);

        const picResponse = await axios(
            {
                url: userResponse.data.data.avatar,
                method: 'GET',
                responseType: 'stream'
            }
        );

        const writer = fs.createWriteStream('./avatar.jpg');
        picResponse.data.pipe(writer);

    } catch (error) {
        console.log(error)
    }
}

getPicByUser(1);

It looks very simple, similar to the syntax of synchronous code. First, get the data of a user, then query the avatar address according to the avatar, and finally write it to a file to save.

  1. Through the syntax of promise.then
    You can also use Promise chain to complete the function you just completed:
axios.get(url + '/1')
    .then(userResponse => axios({
        url: userResponse.data.data.avatar,
        method: 'GET',
        responseType: 'stream'
    }), err => console.log(err))
    .then(picResponse => {
        const writer = fs.createWriteStream('./avatar.jpg');
        picResponse.data.pipe(writer);
    }, err => console.log(err));

node-fetch

1. introduction
Node.js version of the Fetch tool.

Install node fetch:

npm install node-fetch --save
  1. Through aysnc/await

fetch_demo.js:

const fetch = require('node-fetch');
const fs = require('fs');


const url = 'https://reqres.in/api/users';

const getPicByUser = async(user) => {

    let userResponse = await fetch(url + '/' + user);

    let userData = await userResponse.json();

    let picResponse = await fetch(userData.data.avatar);

    const writer = fs.createWriteStream('./avatar.jpg');
    
    picResponse.body.pipe(writer);

}

getPicByUser(1);

Similar to the above code, there is no callback nesting format because of the await keyword.

  1. Through the syntax of promise.then
fetch(url + '/1')
.then(respone => respone.json())
.then(userData => fetch(userData.data.avatar))
.then(picResponse => {
    const writer = fs.createWriteStream('./avatar.jpg');
    picResponse.body.pipe(writer);
});

Summary

It can be seen that it is super convenient to send and receive network requests through Node.js, and it is also very simple to call RESTFul API between different systems. This is also one of my favorite aspects.

Project code

Reference reading

  • https://www.npmjs.com/package/request
  • https://www.npmjs.com/package/axios
  • https://www.npmjs.com/package/node-fetch
  • https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
263 original articles published, 58 praised, 1.02 million visitors+
His message board follow

Topics: axios network npm JSON