Learn the basics of making GET
requests in Vue.js to retrieve information from the backend server.
The easiest way to make HTTP requests in Vue.js is by using axios, a promise based HTTP client for the browser and node.js.
$ npm i axiosNow we can use axios to make HTTP requests.
HTTP GET request example in Vue.js
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
// handle success
commit('SET_LOADED_TODOS', response.data.results)
})
.catch(error => {
// handle error
console.log(error)
})
We’re using a free online REST API server to retrieve a todo-list. You should replace it with your own API paths.
Axios uses ES6 JavaScript Promises, which are supported by most of the up-to-date browsers.
In the example above, we send a GET request to https://jsonplaceholder.typicode.com/todos/1
and store the response in a Vuex store or print an error message in the console if something goes wrong.
JavaScript Promises are making the eventual completion (success or failure of the request) possible.
You can also use a finally()
handler, which is always called after then()
and catch()
handlers (whether the request is fulfilled or rejected).
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
// handle success
console.log(response)
})
.catch(error => {
// handle error
console.log(error)
})
.finally(() => {
// always executed
})
If you find this post useful, please let me know in the comments below.
Cheers,
Renat Galyamov
Want to share this with your friends?
👉renatello.com/vue-js-get-request
PS: Make sure you check other Vue.js tutorials, e.g. how to make a POST request in Vue.js.