This Tutorial builds off the starter application that we generated in the Getting Started with VueJS article.
In this article, we are going to look at how you can use the
axios library to make
HTTP requests within your VueJS 2 applications. The
axios framework is without a doubt the most popular
HTTP frameworks to use within the framework and makes the job of sending requests simple.
In order to install the
axios client, you can use
npm like so:
Let’s attempt to perform a
GET request that will retrieve all of the pokemon from the official Pokemon API that is free to use! We’ll modify the
HelloWorld.vue that is generated with the
vue init webpack command.
We are going to want to perform a
GET request to this Pokemon API on the loading of our component, so in order to do that we are going to want to add the
created lifecycle hook to our
<script/> section and then put our
axios.get() request within that.
axios.get() call returns a promise, when this resolves our
.then() or our
.catch() depending on if our call is successful or whether it returns an error.
Should the request be successful, you should see the Pokemon JSON Response render out within your
The Response Object
Whenever we make a
HTTP request to something, we will get back a
response object that features the following:
You can then do cool things like check to see what status is returned as your response.
If you want to send
POST requests to a service then you certainly can simply by changing the above code to
axios.post(URL). Again, this method returns a promise so you will still need
.catch() to catch the response from this promise.
Say, for example, you had an authorized endpoint that required some headers to be set in order to hit that endpoint. An example of this that I have faced recently was when I needed to hit an authorized API endpoint on AWS. In order for me to hit this endpoint, I had to first set the
We can then make any
HTTP requests as we normally would and it should include the newly set
Alternative Method of Setting Headers
Other HTTP Verbs
Whilst, I have just used the
GET HTTP verbs to demonstrate how you can use axios to send HTTP requests, there are others. These are all of the verbs that you can use to query RESTful API endpoints.
Hopefully, this article showed you everything you need in order to make
HTTP requests within your VueJS applications. If you need further help then please let me know in the comments section below or by tweeting me: @Elliot_F.