Home > front end >  SWAPI Pagination with Node.JS, Express and Axios
SWAPI Pagination with Node.JS, Express and Axios

Time:04-03

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 :

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)

CodePudding user response:

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);
  • Related