Axios is one of the most popular HTTP libraries in Javascript, and we can use it to call apis in Vue programs.

In this article, we use Vue 3 and Axios to write a little app about Kanye West, a nickname that Chinese fans refer to American rapper Kanye West. You can use this app to learn English, and get some inspiration from Kanye’s words. You can also learn to use the Vue asynchronous request API.

Set the basic HTTP request

To install Axios into the project, run the following command from the terminal:

`install axiosnpm install axios  
`
Copy the code

Then, import AXIOS in the Vue component like this.

`//App.vie - importing axios  
<script>  
import axios from 'axios'  
  
export default {  
  setup () {  
    
  }  
}  
</script>  
`
Copy the code

Then use axios.get to retrieve random quotes from the URL of the Kanye REST API. You can then use promise.then to wait for the request to return a response.

`//App.vue - sending our HTTP request  
<script>  
import axios from 'axios'  
  
export default {  
  setup () {  
     axios.get('https://api.kanye.rest/').then(response => {  
        // handle response  
     })  
  }  
}  
</script>  
`
Copy the code

Now that you can get the response from the API, let’s look at what it means. Save it as the quote reference.

`//App.vue - storing the response <script> import axios from 'axios' import { ref } from 'vue' export default { setup ()  { axios.get('https://api.kanye.rest/').then(response => { // handle response quote.value = response }) return { quote }  } } </script> `Copy the code

Output it to the template in italics, enclosed in quotation marks, and add the source of the quote.

`//App.vue - template code  
<template>  
  <div>  
    <i>"{{ quote }}"</i>  
    <p>- Kanye West</p>  
  </div>  
</template>  
`
Copy the code

Check what’s in your browser.

We can see random kanye Quotes returned, along with some additional information, such as the response code to the request.

For our little application, only the data.quote value is of interest, so specify in the script which property on response to access.

`//App.vue - getting only our quote  
axios.get('https://api.kanye.rest/').then(response => {  
        // handle response  
        quote.value = response.data.quote  
})  
`
Copy the code

To get the desired content, use the code above:

Axios async/await

You can combine Axios with async /await mode in a Vue program.

During setup, first comment out the current GET code, and then create an asynchronous method called loadQuote. Internally, we can use the same axios.get method, but we want async to wait for it to complete and then store the result in a constant named Response.

Then set the value of quote.

`//App.vue - async Axios  
const loadQuote = async () => {  
      const response = await KanyeAPI.getQuote()  
      quote.value = response.data.quote  
}  
`
Copy the code

It works exactly the same as the previous code, but in asynchronous mode.

Error handling by Axios

In async-await mode, error handling for API calls can be added with try and catch:

`//Error handling with async/await  
try {  
        const response = await KanyeAPI.getQuote()  
        quote.value = response.data.quote  
} catch (err) {  
        console.log(err)  
}  
`
Copy the code

If you use the original Promises syntax, you can add.catch after the API call to catch any errors from the request.

`//Error handling with Promises  
axios.get('https://api.kanye.rest/')  
      .then(response => {  
        // handle response  
        quote.value = response.data.quote  
      }).catch(err => {  
      console.log(err)  
})  
`
Copy the code

Send a POST request

Let’s look at how to send a POST request. Here we use the JSONPlaceholder Mock API call.

Their documentation provides a /posts interface to test POST requests.

Next we need to create a button that will trigger our API call when clicked. Create a button in the template called “Create Post” and call the createPost method when clicked.

 `<div>  
    <i>"{{ quote }}"</i>  
    <p>- Kanye West</p>  
    <p>  
      <button @click="createPost">Create Post</button>  
    </p>  
  </div>  
</template>`
Copy the code

Now create the createPost method in the code and return it from setup.

This method, which is similar to the previous GET request, just call axios. Post and into the URL (https://jsonplaceholder.typicode.com/posts) you can copy and paste the data in a document.

`//App.vue  
const createPost = () => {  
      axios.post('https://jsonplaceholder.typicode.com/posts', JSON.stringify({  
          title: 'foo',  
          body: 'bar',  
          userId: 1,  
      })).then(response => {  
        console.log(response)  
      })  
}  
`
Copy the code

Click the button to try it out, and you can see a lot of output from the console telling us that the POST request completed successfully.

Write reusable API calls in Axios

Organize all API calls in your project by creating a SRC /services directory.

Directories contain two types of files:

  • Api.js: Used to create an Axios instance with a defined baseURL that will be used for all routes

  • *{specific functionality}* api.js: a more specific file that can be used to organize API calls into reusable modules

The advantage of this is that you can easily switch between development and production servers with only a small code change.

Create the services/ api.js file and set Axios baseURL to the Kanye REST API by default.

`API.jsimport axios from 'axios'  
  
export default(url='https://api.kanye.rest') => {  
    return axios.create({  
        baseURL: url,  
    })  
}  
`
Copy the code

Next create a kanyeapi.js file and import the API from the./API. Here we export the different API calls.

Calling API() gives you an Axios instance in which you can call.get or.post.

`//KanyeAPI.js  
import API from './API'  
  
export default {  
    getQuote() {  
        return API().get('/')  
    },  
}  
`
Copy the code

Then inside app.vue, let our components use this new file through reusable API calls instead of creating Axios themselves.

`//App.vue  
const loadQuote = async () => {  
      try {  
        const response = await KanyeAPI.getQuote() // <--- THIS LINE  
        quote.value = response.data.quote  
      } catch (err) {  
        console.log(err)  
      }  
}  
`
Copy the code

Let’s move createPost into its own reusable method.

Go back to Kanyeapi.js and add createPost in the export default setting, which will pass the data from the POST request as a parameter to our HTTP request.

Like the GET request, you GET the AXIos instance through the API, but this time you override the default URL value and pass the JSONplaceholder URL. Then you can use Axios POST like you used to.

`//KanyeAPI.js  
export default {  
    getQuote() {  
        return API().get('/')  
    },  
    createPost(data) {  
        return API('https://jsonplaceholder.typicode.com/').post('/posts', data)  
    }  
}  
`
Copy the code

So simple

Back at app.vue, you can call the new POST method like this.

`//App.vue   
const createPost = () => {  
      const response = await KanyeAPI.createPost(JSON.stringify({  
          title: 'foo',  
          body: 'bar',  
          userId: 1,  
      }))  
  
      console.log(response)  
}  
`
Copy the code

Now, when you click the button, you can see that the dedicated API works.

The advantage of moving the API calls out of these Vue components and into their own files is that they can be used anywhere in the program. This creates more reusable and scalable code.

The final code

`// App.vue  
<template>  
  <div>  
    <i>"{{ quote }}"</i>  
    <p>- Kanye West</p>  
    <p>  
      <button @click="createPost">Create Post</button>  
    </p>  
  </div>  
</template>  
  
<script>  
import axios from 'axios'  
import { ref } from 'vue'  
import KanyeAPI from './services/KanyeAPI'  
export default {  
  setup () {  
  
    const quote = ref('')  
  
    const loadQuote = async () => {  
      try {  
        const response = await KanyeAPI.getQuote()  
        quote.value = response.data.quote  
      } catch (err) {  
        console.log(err)  
      }  
    }  
  
    loadQuote()  
      
    // axios.get('https://api.kanye.rest/')  
    //   .then(response => {  
    //     // handle response  
    //     quote.value = response.data.quote  
    //   }).catch(err => {  
    //   console.log(err)  
    // })  
  
    const createPost = () => {  
      const response = await KanyeAPI.createPost(JSON.stringify({  
          title: 'foo',  
          body: 'bar',  
          userId: 1,  
      }))  
  
      console.log(response)  
      // axios.post('https://jsonplaceholder.typicode.com/posts', JSON.stringify({  
      //     title: 'foo',  
      //     body: 'bar',  
      //     userId: 1,  
      // })).then(response => {  
      //   console.log(response)  
      // })  
        
    }  
      
    return {  
      createPost,  
      quote  
    }  
  }  
}  
</script>  
  
<style>  
#app {  
  font-family: Avenir, Helvetica, Arial, sans-serif;  
  -webkit-font-smoothing: antialiased;  
  -moz-osx-font-smoothing: grayscale;  
  text-align: center;  
  color: #2c3e50;  
  margin-top: 60px;  
}  
</style>  
`
Copy the code
`//API.js  
import axios from 'axios'  
  
export default(url='https://api.kanye.rest') => {  
    return axios.create({  
        baseURL: url,  
    })  
}  
  
`
Copy the code
`//KanyeAPI.js  
import API from './API'  
export default {  
    getQuote() {  
        return API().get('/')  
    },  
    createPost(data) {  
        return API('https://jsonplaceholder.typicode.com/').post('/posts', data)  
    }  
}  
`
Copy the code

The last

In order to help you better review the key knowledge and prepare for the interview more efficiently, ** “95 pages of front-end Learning Notes” ** electronic draft file is specially organized.

The main content includes HTML, CSS, HTML5, CSS3, JavaScript, regular expressions, functions, BOM, DOM, jQuery, AJAX, VUE and so on.

👉Get it for free here👈

html5/css3

  • The advantage of it

  • HTML5 deprecated Elements

  • New elements in HTML5

  • HTML5 form-related elements and attributes

  • CSS3 added a selector

  • CSS3 Added attributes

  • Added morphing animation properties

  • 3D deformation properties

  • Transition properties of CSS3

  • CSS3 animation properties

  • CSS3 new increment column properties

  • CSS3 added a unit

  • Elastic box model

JavaScript

  • JavaScript based

  • JavaScript data types

  • Arithmetic operations

  • Casts.

  • The assignment operation

  • Relationship between operation

  • Logical operations

  • The ternary operation

  • Branch loop

  • switch

  • while

  • do-while

  • for

  • Break and continue

  • An array of

  • Array methods

  • 2 d array

  • string

Regular expression

  • Creating regular expressions

  • metacharacters

  • Pattern modifier

  • The regular way

  • Support for the String method of re

Js object

  • Define the object

  • Object data access

  • JSON

  • Built-in objects

  • Math methods

  • The Date methods

Object orientation is a programming idea

  • Define the object
  • Prototype and prototype chain
  • Prototype chain
  • The prototype

Common JavaScript design patterns

  • A singleton

  • The factory pattern

  • Case model

function

  • Definition of a function

  • Local variables and global variables

  • The return value

  • Anonymous functions

  • Self-running function

  • closure

BOM

  • Summary of BOM

  • The window method

  • Frames [] Frames set

  • History Historical records

  • The location positioning

  • The navigator navigation

  • Screen screen

  • The document document

DOM

  • DOM object methods
  • Manipulating relationships between DOM’s
  • DOM node attributes

The event

  • Event classification

  • The event object

  • Flow of events

  • Event goals

  • Event delegate

  • Event listeners

jQuery

  • JQuery selector

  • Property selector

  • Position selector

  • Descendant selector

  • Child selector

  • Selector object

  • Child elements

  • DOM manipulation

  • JQuery event

  • Container to adapt

  • Label style manipulation

  • sliding

  • Custom animation

AJAX

  • The working principle of
  • The XMLHttpRequest object
  • Differences between XML and HTML
  • The get () and post ()

HTTP

  • HTTP message structure

  • Url Request process

Performance optimization

  • JavaScript code optimization
  • Improves file loading speed

webpack

  • The characteristics of the webpack

  • The disadvantage of webpack

  • The installation

  • Webpack basic application

  • Getting Started with Configuration Files

vue

  • The MVC pattern

  • The MVVM pattern

  • Basic grammar

  • Instance properties/methods

  • The life cycle

  • Calculate attribute

  • Array update check

  • The event object

  • Vue components

  • Routing using

  • Routing navigation

  • Embedded routines by

  • Named view

👉Get it for free here👈