Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Axios to request API asynchronously by Vue

2025-01-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

Today, I would like to share with you how Vue uses Axios to request API asynchronously. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Set up basic HTTP request

First, execute the following command in the terminal to install Axios into the project:

Install axiosnpm install axios

Then, import the axios like this in the Vue component.

/ / App.vie-importing axios import axios from 'axios' export default {setup () {}}

Next, use axios.get to get random quotations through Kanye REST API's URL. You can then use Promise.then to wait for the request to return a response.

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

Now that you can get the response from API, take a look at what it means. Save it as a reference named quote.

/ / App.vue-storing the response 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}}

Finally, output it to the template and display it in italics, and quote it in quotation marks. You also need to add the citation source to the quotation.

/ / App.vue-template code "{{quote}}"

-Kanye West

Check the contents of the browser.

We can see the Kanye quotes returned at random, as well as some additional information, such as the response code of the request.

For our applet, we are only interested in this data.quote value, so specify which property on the response you want to access in the script.

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

You can get what you want through the above code:

Axios with async/await

You can use Axios in combination with async / await mode in Vue programs.

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

Then set the value of quote.

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

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

Error handling of Axios

In async-await mode, you can add error handling for API calls through try and catch:

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

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

/ / Error handling with Promises axios.get ('https://api.kanye.rest/') .then (response = > {/ / handle response quote.value = response.data.quote}) .catch (err = > {console.log (err)}) sends a POST request

Let's take a look at how to send POST requests. Here we use the JSONPlaceholder Mock API call.

Their documentation provides a / posts interface for testing POST requests.

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

"{{quote}}"

-Kanye West

Create Post

Template >

Let's create the createPost method in the code and return from setup.

This method, similar to the previous GET request, simply calls axios.post and passes in URL (that is, https://jsonplaceholder.typicode.com/posts) to copy and paste the data in the 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)})}

Click the button to try, and you can see that the console outputs a lot of information telling us that the POST request has been completed successfully.

Writing reusable API calls with Axios

Organize all api calls in the project by creating a src/services directory.

The directory contains 2 types of files:

API.js: used to create an Axios instance with a defined baseURL, which 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 it is easy to switch between development and production servers, with only a small amount of code to be modified.

Create a services/API.js file and set Axios baseURL to default to Kanye REST API.

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

Next, create a KanyeAPI.js file and import API from. / API. Here we are going to export different API calls.

Calling API () gives you an instance of Axios where you can call .get or .post.

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

Then within App.vue, let our components use the new file through reusable API calls instead of creating the Axios themselves.

/ / App.vue const loadQuote = async () = > {try {const response = await KanyeAPI.getQuote () / / {const response = await KanyeAPI.createPost (JSON.stringify ({title: 'foo', body:' bar', userId: 1,}) console.log (response)}

Now when you click the button, you can see that the dedicated API is working properly.

The advantage of removing API calls from these Vue components and placing them in its own file is that these API calls can be used anywhere in the program. This creates more reusable and scalable code.

Final code / / App.vue "{{quote}}"

-Kanye West

Create Post

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}} # 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 } / / API.js import axios from 'axios' export default (url=' https://api.kanye.rest') = > {return axios.create ({baseURL: url,})} / / KanyeAPI.js import API from'. / API' export default {getQuote () {return API () .get ('/')} CreatePost (data) {return API ('https://jsonplaceholder.typicode.com/').post('/posts', data)}} these are all the contents of the article "how to use Axios to request API asynchronously by Vue" Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 233

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report