Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Vue Communicates with the Internet Chapter 14

Sending basic AJAX requests with Axios


Axios is the recommended library for Vue for making HTTP requests. It's a very simple


library, but it has some built-in features that help you in carrying out common operations.
It implements a REST pattern for making requests with HTTP verbs and can also deal with


concurrency (spawning multiple requests at the same time) in a function call. You can find
more information at https://github.com/mzabriskie/axios.


Getting ready


For this recipe, you don't need any particular knowledge of Vue. We will use Axios, which
itself uses JavaScript promises. If you have never heard of promises, you can have a primer


at https:/​/​developers.​google.​com/​web/​fundamentals/​getting-​started/​primers/


promises.


How to do it...


You will build a simple application that gives you a wise piece of advice every time you


visit the web page.


The first thing you will need is to install Axios in your application. If you are using npm,


you can just issue the following command:


npm install axios

If you are working on a single page, you can import the following file from CDN,


at https:/​/​unpkg.​com/​axios/​dist/​axios.​js.


Unfortunately, the advise slip service we will use will not work with
JSFiddle because while the service runs on HTTP, JSFiddle is on HTTPS
and your browser will most likely complain. You can run this recipe on a
local HTML file.

Our HTML looks like this:


<div id="app">
<h2>Advice of the day</h2>
<p>{{advice}}</p>
</div>
Free download pdf