进行多个 Node Express API 请求调用

Making multiple Node Express API request calls

我按照本指南 https://herewecode.io/blog/step-by-step-guide-create-first-api-with-node-express/ 创建了一个简单的节点,Express API 并且一切正常,然后我更改了 API 调用以与 SW[=32= 交互](星球大战API)。再次一切正常。但我的问题是,如果我想多次调用 SWAPI 并获得 2 或 3 个响应并将它们一起显示,我该怎么做?快递请求是最好的选择吗?

GitHub 指南:https://github.com/gael-thomas/First-API-With-Node-And-Express-example

这是我的基本应用程序,在路线上有 API 呼叫

Index.js

const express = require('express')
const api_helper = require('./API_helper')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Welcome to Make REST API Calls In Express!'))

app.get('/getAPIResponse', (req, res) => {
  api_helper.make_API_call('https://swapi.dev/api/people/1/')
    .then(response => {
      console.log(response[0])
      res.json(response)
    })
    .catch(error => {
      res.send(error)
    })
})

app.listen(port, () => console.log(`App listening on port ${port}!`))

module.exports = app

API_helper.js

const request = require('request')

module.exports = {
  make_API_call : function(url){
    return new Promise((resolve, reject) => {
      request(url, { json: true }, (err, res, body) => {
        if (err)
          reject(err)
        resolve(body)
      });
    })
  }
}

那么我在哪里调用 https://swapi.dev/api/people/1/ 并得到我的响应我将如何调用 /people/2//people/3/ 并将它们一起显示?

Promise.all([
  api_helper.make_API_call('https://swapi.dev/api/people/1/'),
  api_helper.make_API_call('https://swapi.dev/api/people/2/'),
  api_helper.make_API_call('https://swapi.dev/api/people/3/')
])
.then(function([response1, response2, response3]) {
  // Process the three responses
})
.catch(error => {
  // Error occurred in any of the three requests
  res.send(error)
});

找到了使用 axios 的方法,只需在顶部要求它并且可以进行多次调用并将所有响应组合在一起。

const express = require('express')
const app = express()
const port = 3000
const axios = require("axios")

app.get('/', (req, res) => res.send('Welcome to Make REST API Calls In Express!'))

app.get('/getAPIResponse', (req, res) => {

let one =
"https://swapi.dev/api/people/1/";
let two =
"https://swapi.dev/api/people/2/";
let three =
"https://swapi.dev/api/people/3/";

const requestOne = axios.get(one);
const requestTwo = axios.get(two);
const requestThree = axios.get(three);

axios
  .all([requestOne, requestTwo, requestThree])
  .then(
    axios.spread((...responses) => {
      const responseOne = responses[0].data;
      const responseTwo = responses[1].data;
      const responseThree = responses[2].data;

      const combined = {responseOne, responseTwo, responseThree}

      res.send(combined)
    })
  )
  .catch(errors => {
    // react on errors.
    console.error(errors);
  });
})

app.listen(port, () => console.log(`App listening on port ${port}!`))

module.exports = app