fetch data from api with parameters code example

Example 1: get data from fetch api into variable

<script>
function getFromAPI(url, callback){
  var obj;
  fetch(url)
    .then(res => res.json())
    .then(data => obj = data)
    .then(() => callback(obj))
 }

getFromAPI('https://jsonplaceholder.typicode.com/posts', getData);

function getData(arrOfObjs){
  var results = "";
  arrOfObjs.forEach( (x) => {
    results += "<p> Id: " + x.id + "<ul>"
    Object.keys(x).forEach( (p) => {
        results += "<li>" + (p + ": " + x[p]) + "</li>";
    });
    results += "</ul> </p> <hr>"
  })
  results += "";
  document.getElementById("myDiv").innerHTML = results;
}

</script>

Example 2: fetch and then javascript send parameters

const url = 'https://randomuser.me/api';
// The data we are going to send in our request
let data = {
    name: 'Sara'
}
// The parameters we are gonna pass to the fetch function
let fetchData = { 
    method: 'POST', 
    body: data,
    headers: new Headers()
}
fetch(url, fetchData)
.then(function() {
    // Handle response you get from the server
});