Sending a GET request


What is a GET request?

GET request is the most commonly used kind of request on the web. 

GET request is usually (and not always) used to fetch some sort of data from a URL. 

In Vue applications we use GET requests in JSON format. 


Sending GET requests with Axios

We learned how to define data, but until now we were hard-coding the values. 

Let's send a GET request via axios to a sample JSON address that I've created to fetch and initialize our data values:

new Vue({
el: '#app',
data: {
firstname: '',
lastname: '',
age: '',
country: ''
},
created() {
this.fetchData();
},
methods: {
fetchData() {
axios.get('https://vue-school.com/api/sample-json').then(response => {
this.firstname = response.data.firstname;
this.lastname = response.data.lastname;
this.age = response.data.age;
this.country = response.data.country;
});
}
}
});

And display values to see the result:

<div id="app">
<p>Firstname: {{ firstname }}</p>
<p>Lastname: {{ lastname }}</p>
<p>Age: {{ age }}</p>
<p>Country: {{ country }}</p>
</div>

Sending parameters

In some cases you might need to send some parameters to a route to receive some specific response. There are two ways of doing so with Axios. You could either do it via the classic ugly syntax:

axios.get('/user?ID=12345').then(response => {
console.log(response);
});

Or send the parameters via the "params" object:

axios.get('/user', {
params: {
ID: 12345
}
}).then(response => {
console.log(response);
});

Comments: