Reputation: 3329
I wrote an API using Node JS and Express and I have a json file with an array of 150 objects. The API code that sends the entire json looks like this:
app.get("/api/pokemons", function (req, res) {
res.setHeader("Content-Type", "application/json");
let rawdata = fs.readFileSync("assets/pokemons.json");
let pokemons = JSON.parse(rawdata);
res.send(pokemons);
});
This code works perfectly when I fetch it in the HTML file:
var parentDOM = document.getElementById("test");
fetch("http://localhost:8000/api/pokemons")
.then((response) => response.json())
.then((data) =>
{
//console.log(data)
data.forEach(element =>
parentDOM.innerHTML += "Pokemon: "+element.name+" ID: " +element.id +"</br>"
);
});
but I am looking for a way to fetch only one ID at a time and send it to the client to a designed HTML file because I have 151 objects. I want to have a file, let's say pokemon.html and access to IDs using the browser - for instance when I go to http://localhost:8000/api/pokemon.html/2
To fetch all the objects from the json file I used pure JS and it worked. Is there a way to pass a parameter to a HTML file so I can then check the ID and fetch the specific json object?
Thank you!
Upvotes: 0
Views: 1320
Reputation: 10490
Yes you can define parameters in your url
app.get("/api/pokemons/:id", function (req, res) {
res.setHeader("Content-Type", "application/json");
let rawdata = fs.readFileSync("assets/pokemons.json");
let pokemons = JSON.parse(rawdata);
pokemons.filter(x=> x.id == req.params.id)
res.send(pokemons);
});
Edit: i think I missunderstood the question to read parameters in the html file
you can do if you have an url
http://localhost:8000/api/pokemon.html?id=2
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
urlParams.get('id')//will return 2
if the url is like this and your certain
http://localhost:8000/api/pokemon.html/2
you could just split
const queryString = window.location.href
let parts = queryString.split('/')
let id = parts[parts.length-1]
Upvotes: 2