POST Request with Fetch API?

Rob picture Rob · Sep 19, 2016 · Viewed 75.5k times · Source

I know that with the new Fetch API (used here with ES2017's async/await) you can make a GET request like this:

async getData() {
    try {
        let response = await fetch('https://example.com/api');
        let responseJson = await response.json();
        console.log(responseJson);
    } catch(error) {
        console.error(error);
    }
}

But how do you make a POST request?

Answer

hellojebus picture hellojebus · Sep 19, 2016

Long story short, Fetch also allows you to pass an object for a more personalized request:

fetch("http://example.com/api/endpoint/", {
  method: "post",
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },

  //make sure to serialize your JSON body
  body: JSON.stringify({
    name: myName,
    password: myPassword
  })
})
.then( (response) => { 
   //do something awesome that makes the world a better place
});

Check out the fetch documentation for even more goodies and gotchas:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Please note that since you're doing an async try/catch pattern, you'll just omit the then() function in my example ;)