gengns ES

An entry from the gengns log, written by Génesis García Morilla · · JavaScript

Post JSON data to an URL

The easiest way to do a POST in JavaScript: using fetch.

Result of the demo “Post JSON data to an URL”

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);
  });

HTML

<div></div>
Open in JSFiddle

Tags: AJAX, fetch, HTTP, JSON, post, promises