make a http post request in javascript

To make an HTTP POST request in JavaScript, you can use the built-in fetch API or XMLHttpRequest (XHR) object.

Using fetch API:

index.tsx
fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
227 chars
11 lines

Using XMLHttpRequest (XHR):

index.tsx
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.response);
  }
  else {
    console.error(xhr.statusText);
  }
};
xhr.onerror = function() {
  console.error(xhr.statusText);
};
xhr.send(JSON.stringify(data));
350 chars
16 lines

gistlibby LogSnag