DEV Community

Krunal Kanojiya
Krunal Kanojiya

Posted on

POST Request in Javascript with Fetch() and XMLHttpRequest

To make a POST request in JavaScript, you can use the fetch() method or the XMLHttpRequest object.

Here's an example using fetch():

fetch('https://example.com/api/create', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'John Smith',
    email: 'john@smith.com'
  })
})
.then(response => response.json())
.then(data => console.log(data));
Enter fullscreen mode Exit fullscreen mode

And here's an example using XMLHttpRequest:

var xhr = new XMLHttpRequest();

xhr.open('POST', 'https://example.com/api/create', true);
xhr.setRequestHeader('Content-Type', 'application/json');

xhr.onload = function () {
  if (this.status === 200) {
    console.log(this.response);
  }
};

xhr.send(JSON.stringify({
  name: 'John Smith',
  email: 'john@smith.com'
}));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)