Place an ID on each of the HTML elements that will receive the information, for example using a Bootstrap 4 card:
<div class="card shadow" style="width: 18rem;">
<img id="avatar" class="card-img-top" src="#" alt="Image">
<div class="card-body">
<h5 id="first_name" class="card-title"></h5>
<p id="last_name" class="card-text"></p>
</div>
</div>
Use the fetch
of Javascript passing the URL of your API, in this example to put the data and the image of a user on the previous card we do:
const url = 'https://reqres.in/api/users/2'; // Troque pela URL da sua API
function readJson() {
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error("Erro HTTP: " + response.status);
}
return response.json();
})
.then(json => {
this.response = json;
document.getElementById('avatar').src = response.data.avatar;
document.getElementById('first_name').innerHTML = response.data.first_name;
document.getElementById('last_name').innerHTML = response.data.last_name;
})
.catch(function () {
this.dataError = true;
})
}
readJson();
Follows the link of this example in operation.
This will work, but I have a local JSON as I could find it through the const url = '.. /Assets/products.json' would be this way?
– Thales Henrique
You should install a web server locally and use localhost with your URL.
– Thiago Krempser
I was able to host it on a https://thaleshenrique38.000webhostapp.com/products.json. but even putting the URL and ID’s the same as the application ends up not being able to consume!
– Thales Henrique
As you have several items, try building a loop to catch them one by one. To get the image, in your case it changes a little because of the array that your API returns, then it would look something like Response.data.images[0]. imageurl.
– Thiago Krempser