Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SWAPI Pagination with Node.JS, Express and Axios

I wanted to fetch all people/films/etc. from SWAPI.

I tried a lot of things before finally get something usable. However, it only shows the first 10. people (in the people case)

const express = require("express");
const router = express.Router();
const axios = require("axios");

router.get("/people", (req, res) => {
  axios
    .get("https://swapi.dev/api/people/?format=json")
    .then((data) => {
      return res.send(data.data.results);
    })
    .catch((error) => {
      console.log("error: ", error);
    });
});

module.exports = router;

What I tried, thanks to a lot of searches from Stack Overflow, is this :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const express = require("express");
const router = express.Router();
const axios = require("axios");

router.get("/people", async (req, res) => {

  let nextPage = `https://swapi.dev/api/people/`;
  let people = [];
  while (nextPage) {
    res = await axios(nextPage)
    const { next, results } = await res.data;

    nextPage = next

    people = [...people, ...results]
  } 
  console.log(people.length) // 82
  console.log(people) // shows what I wanted, all people !
  return people;


});

module.exports = router;

When starting the server, the page doesn’t finish loading (it’s still loading at this moment), but the console.log managed to show exactly what I wanted.

So, how can I manage to show this in the page ?

My goal is to use that route for axios API calls from a React front-end (searching for a specific name)

>Solution :

Do not overwrite the res in your code and finish it with res.send:

let nextPage = `https://swapi.dev/api/people/`;
let people = [];
while (nextPage) {
  let nextres = await axios(nextPage)
  const { next, results } = await nextres.data;
  nextPage = next
  people = [...people, ...results]
} 
console.log(people.length) // 82
console.log(people) // shows what I wanted, all people !
res.send(people);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading