Vue Return Request

Posted on  by admin

Below is a quick set of examples to show how to send HTTP GET requests from Vue to a backend API using the axios HTTP client which is available on npm.

Other HTTP examples available:. Vue + Axios: POST.

Vue + Fetch: GET, POST. React + Fetch: GET, POST, PUT, DELETE. React + Axios: GET, POST, PUT, DELETE.

POST request using fetch with async/await

Angular: GET, POST, PUT, DELETE. Blazor WebAssembly:GET, POST.

Axios: GET, POST, PUT, DELETE. Fetch: GET, POST, PUT, DELETE. With the npm CLI: npm install axios. With the yarn CLI: yarn add axios.

GET request using axios with set HTTP headers

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.

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

This sends the same GET request from Vue using axios, 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).

Example Vue component at https://codesandbox.io/s/vue-axios-http-get-request-examples-ei7l8?file=/app/GetRequestAsyncAwait.vue. This sends a GET request from Vue to an invalid url on the npm api then assigns the error message to the errorMessage component data property and logs the error to the console.

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

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

Example Vue component at https://codesandbox.io/s/vue-axios-http-get-request-examples-ei7l8?file=/app/GetRequestSetHeaders.vue.