Published: June 09 2022

Vue + Fetch - HTTP PUT Request Examples

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

Other HTTP examples available:


Simple PUT request with a JSON body using fetch

This sends an HTTP PUT request to the Reqres api which is a fake online REST api that includes a generic /api/<resource> route that responds to PUT requests for any <resource> with the contents of the request body and an updatedAt property with the current date. This example sends an article object to the /api/articles/1 route and then assigns the updatedAt date from the response to the vue component data property updatedAt so it can be displayed in the component template.

created() {
  // Simple PUT request with a JSON body using fetch
  const requestOptions = {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title: "Vue PUT Request Example" })
  };
  fetch("https://reqres.in/api/articles/1", requestOptions)
    .then(response => response.json())
    .then(data => (this.updatedAt = data.updatedAt));
}

Example Vue component at https://codesandbox.io/s/vue-fetch-http-put-request-examples-g1h11z?file=/app/PutRequest.vue


PUT request using fetch with async/await

This sends the same PUT 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() {
  // PUT request using fetch with async/await
  const requestOptions = {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title: "Vue PUT Request Example" })
  };
  const response = await fetch("https://reqres.in/api/articles/1", requestOptions);
  const data = await response.json();
  this.updatedAt = data.updatedAt;
}

Example Vue component at https://codesandbox.io/s/vue-fetch-http-put-request-examples-g1h11z?file=/app/PutRequestAsyncAwait.vue


PUT request using fetch with error handling

This sends a PUT request from Vue using fetch to an invalid url on the api then assigns the error message to the errorMessage component data 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() {
  // PUT request using fetch with error handling
  const requestOptions = {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ title: 'Vue PUT Request Example' })
  };
  fetch('https://reqres.in/invalid-url', requestOptions)
    .then(async response => {
      const isJson = response.headers.get('content-type').includes('application/json');
      const data = isJson && 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.updatedAt = data.updatedAt;
    })
    .catch(error => {
      this.errorMessage = error;
      console.error('There was an error!', error);
    });
}

Example Vue component at https://codesandbox.io/s/vue-fetch-http-put-request-examples-g1h11z?file=/app/PutRequestErrorHandling.vue


PUT request using fetch with set HTTP headers

This sends the same PUT 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() {
  // PUT request using fetch with set headers
  const requestOptions = {
    method: 'PUT',
    headers: { 
      'Content-Type': 'application/json',
      'Authorization': 'Bearer my-token',
      'My-Custom-Header': 'foobar'
    },
    body: JSON.stringify({ title: 'Vue PUT Request Example' })
  };
  fetch('https://reqres.in/api/articles/1', requestOptions)
    .then(response => response.json())
    .then(data => this.updatedAt = data.updatedAt);
}

Example Vue component at https://codesandbox.io/s/vue-fetch-http-put-request-examples-g1h11z?file=/app/PutRequestSetHeaders.vue

 


Need Some Vue Help?

Search fiverr for freelance Vue developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by