Post JSON data to an URL

by Génesis García Morilla

HTML

<div></div>

JavaScript

const $div = document.querySelector('div');

// If you don't need user and password, delete headers (we are just using it for that)
fetch('/echo/json/', {
    headers: {
      "Authorization": "Basic " + btoa(`user:password`)
    },
    method: 'post',
    body: JSON.stringify({
      animal: 'dog'
    })
  })
  .then(response => {
    if (response.ok) $div.textContent = 'Ok';
    else alert(response.statusText);
  });