简体   繁体   中英

How can I merge results from multiple REST endpoints?

I am new to Express.

I am creating a new API endpoint, which is getting data from two other publically available endpoints. Once I get the JSON from both APIs, I will merge them according to some rules.

let result1, result2;

// API 1
let data1;
app.get("/test1", (req, res, next) => {
  axios.get("https://www.EXAMPLE.com/api/endpoint_A")
  .then((response) => {
     res.json(response.data)
     data1 = response.data;
  });
});

// API 2
let data2;
app.get("/test2", (req, res, next) => {
  axios.get("https://www.EXAMPLE.com/api/endpoint_B")
  .then((response) => {
     res.json(response.data)
     data2 = response.data;
  });
});

console.log(data1); //output is undefined
console.log(data2); //output is undefined

I can see result of successful calls in both the browser and in Postman.

My problem is, that I cannot find a way to manipulate the result of each endpoint. I have tried to store like this result1 = response.data in the then but it is undefined . Once I can access the output of each response, then I have to merge them. But accessing the results outside the axios call appears to be more difficult. I don't have to use axios .

I also tried this but it didn't work.

// API 1
const data1 = app.get("/test1", (req, res, next) => {
  axios.get("https://www.EXAMPLE.com/api/endpoint_A")
  .then((response) => res.json(response.data));
});

console.log(data1); //output is undefined

as far as im aware data does not persist between api calls. you could combine that into a single endpoint.

 //Both apis into one endpoint app.get('/test', (req, res, next) => { const promiseArr = [axios.get('https://www.EXAMPLE.com/api/endpoint_A'), axios.get('https://www.EXAMPLE.com/api/endpoint_B')]; Promise.all(promiseArr).then(responses => { const resultsFromEndpointA = responses[0]; const resultsFromEndpointB = responses[1]; //do what you want with your results here... for example.. return res.status(200).json({resultsFromEndpointA, resultsFromEndpointB}); //or do something like load them into a session req.session.results = {resultsFromEndpointA, resultsFromEndpointB}; next(); }).catch(err => { console.log(err); }); };

If you are getting an array of objects with the same properties from the both endpoints, do this;


let results = [];

// API 1
app.get("/test1", (req, res, next) => {
  axios
    .get(
      "https://www.EXAMPLE.com/api/endpoint_A"
    )
    .then((response) => {
      results.push(response.data);
    });
});

// API 2
app.get("/test2", (req, res, next) => {
  axios
    .get(
      "https://www.EXAMPLE.com/api/endpoint_B"
    )
    .then((response) => {
      results.push(response.data);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM