How do I get only a defined amount of attributes of my Express API with a browser?

Issue

Let me give an example: By accessing the following page we have access to all JSON code: https://jsonplaceholder.typicode.com/todos

But if I want I can retrieve just the first 6 elements of the JSON by accessing the following: https://jsonplaceholder.typicode.com/todos?_limit=6

I want to do this same thing with my Express code that I am accessing with http://localhost:3100

When I try http://localhost:3100?_limit=6 it brings the entire JSON file, I don’t understand why. How can I fix this? I want the browser to be able to limit the amount that it gets from the API.

Here is my Express code:

const express = require("express");

const app = express();

const projects = [
  { project: "Challenges_jschallenger.com" },
  { project: "Using-Studio-Ghilis-API-With-JS-Only" },
  { project: "my-portfolio-next" },
  { project: "Youtube-Navbar-2021" },
  { project: "Mana-raWozonWebsite" },
  { project: "Movies-Website" },
  { project: "Add-Remove-Mark-and-Mark-off-With-ReactJS" },
  { project: "My-Portfolio" },
  { project: "Github_Explorer" },
  { project: "MestreALMO.github.io" },
  { project: "Tests-With-useState-useEffect-useRef" },
  { project: "Tic-Tac-Toe-React-in-JS" },
  { project: "ReactJS-with-TypeScript-Template" },
  { project: "Retractable-Accordion" },
];

app.get("/", function (req, res) {
  res.send(projects);
});

app.listen(3100);

Solution

You need to extract the query from the express request. Also the correct way to respond with a json object would be to call the json method.

app.get("/", (req, res) => {
  const { limit } = req.query
  res.json(projects.slice(0, limit))
})

For it to work you would have to make the request to http://localhost:3100/?limit=6

Answered By – jmpargana

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published