I am trying to show my data obtained from my API but it is not shown I am using JS.
fetch (" http://127.0.0.1:8000/api/vehiculo/ ") .then (res => res.json ()) .then (data => muestraData (data))
const muestraData = (data) => {
let body = ''
for (let i = 0; i <data.length; i ++) {
body + = <tr><td>${data[i].id}</td></tr>
}
document.getElementById('data').innerHTML = body
}
First of all, I don't know how your API response is look like, so in this explanation, I will use (Rick-and-Morty APIs).
Let's make a function to fetch the data from API:
const loadData = () => {
return fetch("https://rickandmortyapi.com/api/character")
.then((response) => response.json())
.catch((error) => {
throw error;
});
};
Now we can call loadData function and build the body:
const data = document.getElementById("data");
loadData().then((response) => {
const results = response.results;
let body = "";
if (results && results.length > 0) {
results.forEach((item) => {
body += `ID: ${item.id} <br/>`;
});
}
data.innerHTML = body;
});
Because the
resultsvariable contains an array of objects, we can just use the.forEachmethod.
loadDatareturnsPromise
Working example: