JSON POST with Response

A simple method of posting JSON data using the window.fetch() method and receiving a response. In this scenario it was an empty response set but with a status indicator, such as an integer 204 indicating that the API accepted was posted.

JavaScript

window.fetch("api-post url", {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
    key: 'value'
  })
    }).then((response) => { 
       if (response.status === [expectedResponse])
       {
         alert("succesful!");
       }
       else if (response.status === [rejectedResponse]) 
       {
         alert ("not succesful :-(");
       };
    })
    .catch(error => console.error(error.message));

Its not perfect, and won’t suit posts that require more data to be submitted, but it’ll do for now.