Published: April 30 2020

Vue + Fetch - HTTP GET Request Examples

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

Other HTTP examples available:


Simple GET request using fetch

This sends an HTTP GET request from Vue to the npm api to search for all vue packages using the query q=vue, then assigns the total returned in the response to the component data property totalVuePackages so it can be displayed in the component template.

created() {
  // Simple GET request using fetch
  fetch("https://api.npms.io/v2/search?q=vue")
    .then(response => response.json())
    .then(data => (this.totalVuePackages = data.total));
}

Example Vue component at https://codesandbox.io/s/vue-fetch-http-get-request-examples-rzuqn?file=/app/GetRequest.vue


GET request using fetch with async/await

This sends the same GET 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() {
  // GET request using fetch with async/await
  const response = await fetch("https://api.npms.io/v2/search?q=vue");
  const data = await response.json();
  this.totalVuePackages = data.total;
}

Example Vue component at https://codesandbox.io/s/vue-fetch-http-get-request-examples-rzuqn?file=/app/GetRequestAsyncAwait.vue


GET request using fetch with error handling

This sends a GET request from Vue to an invalid url on the npm api then assigns the error 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() {
  // GET request using fetch with error handling
  fetch("https://api.npms.io/v2/invalid-url")
    .then(async response => {
      const data = await response.json();

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

      this.totalVuePackages = data.total;
    })
    .catch(error => {
      this.errorMessage = error;
      console.error("There was an error!", error);
    });
}

Example Vue component at https://codesandbox.io/s/vue-fetch-http-get-request-examples-rzuqn?file=/app/GetRequestErrorHandling.vue


GET request using fetch with set HTTP headers

This sends the same GET request again from Vue using fetch with the HTTP Content-Type header set to application/json.

created() {
  // GET request using fetch with set headers
  const headers = { "Content-Type": "application/json" };
  fetch("https://api.npms.io/v2/search?q=vue", { headers })
    .then(response => response.json())
    .then(data => (this.totalVuePackages = data.total));
}

Example Vue component at https://codesandbox.io/s/vue-fetch-http-get-request-examples-rzuqn?file=/app/GetRequestSetHeaders.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