Published: April 30 2020

Vue + Fetch - HTTP POST Request Examples

Below is a quick set of examples to show how to send HTTP POST requests from Vue to a backend API using fetch() which comes bundled with all modern browsers.

Other HTTP examples available:


Simple POST request with a JSON body using fetch

This sends an HTTP POST request to the JSONPlaceholder api which is a fake online REST api that includes a /posts route that responds to POST requests with the contents of the post body and an id property. The id from the response is assigned to the vue component data property postId so it can be displayed in the component template.

created() {
  // Simple POST request with a JSON body using fetch
  const requestOptions = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title: "Vue POST Request Example" })
  };
  fetch("https://jsonplaceholder.typicode.com/posts", requestOptions)
    .then(response => response.json())
    .then(data => (this.postId = data.id));
}

Example Vue component at https://codesandbox.io/s/vue-fetch-http-post-request-examples-4i038?file=/app/PostRequest.vue


POST request using fetch with async/await

This sends the same POST request from Vue using fetch, but this version uses an async function and the await javascript expression to wait for the promises to return (instead of using the promise then() method as above).

async created() {
  // POST request using fetch with async/await
  const requestOptions = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title: "Vue POST Request Example" })
  };
  const response = await fetch("https://jsonplaceholder.typicode.com/posts", requestOptions);
  const data = await response.json();
  this.postId = data.id;
}

Example Vue component at https://codesandbox.io/s/vue-fetch-http-post-request-examples-4i038?file=/app/PostRequestAsyncAwait.vue


POST request using fetch with error handling

This sends a POST request from Vue to an invalid url on the api then assigns the error to the errorMessage component state property and logs the error to the console.

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response.ok property to see if the request failed and reject the promise ourselves by calling return Promise.reject(error);. This approach means that both types of failed requests - network errors and http errors - can be handled by a single catch() block.

created() {
  // POST request using fetch with error handling
  const requestOptions = {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ title: 'Vue POST Request Example' })
  };
  fetch('https://jsonplaceholder.typicode.com/invalid-url', requestOptions)
    .then(async response => {
      const data = await response.json();

      // check for error response
      if (!response.ok) {
        // get error message from body or default to response status
        const error = (data && data.message) || response.status;
        return Promise.reject(error);
      }

      this.postId = data.id;
    })
    .catch(error => {
      this.errorMessage = error;
      console.error('There was an error!', error);
    });
}

Example Vue component at https://codesandbox.io/s/vue-fetch-http-post-request-examples-4i038?file=/app/PostRequestErrorHandling.vue


POST request using fetch with set HTTP headers

This sends the same POST request again from Vue using fetch with a couple of extra headers set, the HTTP Authorization header and a custom header My-Custom-Header.

created() {
  // POST request using fetch with set headers
  const requestOptions = {
    method: 'POST',
    headers: { 
      'Content-Type': 'application/json',
      'Authorization': 'Bearer my-token',
      'My-Custom-Header': 'foobar'
    },
    body: JSON.stringify({ title: 'Vue POST Request Example' })
  };
  fetch('https://jsonplaceholder.typicode.com/posts', requestOptions)
    .then(response => response.json())
    .then(data => this.postId = data.id);
}

Example Vue component at https://codesandbox.io/s/vue-fetch-http-post-request-examples-4i038?file=/app/PostRequestSetHeaders.vue

 


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

Other than coding...

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.


Need Some Vue Help?

Search fiverr to find help quickly from experienced Vue developers.



Supported by