Home > Web Front-end > Vue.js > How to use Axios to implement asynchronous requests and data interaction under Vue?

How to use Axios to implement asynchronous requests and data interaction under Vue?

WBOY
Release: 2023-06-27 09:47:37
Original
1739 people have browsed it

Vue is a widely used JavaScript framework that supports many popular libraries and plugins, including Axios. Axios is a Promise-based HTTP library that enables asynchronous requests and data interaction in Vue applications.

In this article, we will learn how to use Axios to implement asynchronous requests and data interaction in Vue applications. Specifically, we'll look at the basics of Axios, including how to use it within a Vue component, how to set up Axios' default configuration, and cover how to use Axios interceptors and error handling.

Preparation

Before using Axios, we need to install it in the Vue application. Installing Axios is very simple, just run the following command in the terminal:

npm install axios
Copy after login

After installing Axios, we can use it in the Vue component. We need to import the Axios library in the Vue component and create an Axios instance using the following code:

import axios from 'axios';

const axiosInstance = axios.create({
  baseURL: 'https://api.example.com',
});
Copy after login

baseURL is the root URL of the API we will access.

After completing the installation and configuration of Axios, let's start implementing asynchronous request data interaction.

Initiate asynchronous requests

Axios uses promises to manage asynchronous requests. We can use different methods of the Axios instance to send different types of requests, including GET, POST, PUT, DELETE, etc. Don't worry about these, I will explain the implementation of each method in detail below.

GET request

GET is the most commonly used method in Axios. It is used to obtain resources from the API. We can use the get method of the Axios instance to initiate a GET request. For example:

axiosInstance.get('/users')
  .then(response => console.log(response.data));
Copy after login

This request will use the default Axios configuration and send a GET request from https://api.example.com/users. Upon success, we will see the response data in the console.

POST request

POST request is often used to send data to the API, such as user login, registration or providing data. You can use the post method of the Axios instance to initiate a POST request. For example:

axiosInstance.post('/login', {
  username: 'JohnDoe',
  password: 'secret'
})
.then(response => console.log(response.data));
Copy after login

will send a POST request to https://api.example.com/login with an object containing username and password as parameters. Upon success, we will see the response data in the console.

PUT request

PUT request is often used to update existing resources. You can use the put method of the Axios instance to initiate a PUT request. For example:

axiosInstance.put('/users/1', {
  name: 'John Doe'
})
.then(response => console.log(response.data));
Copy after login

will send a PUT request to https://api.example.com/users/1 with an object containing updated data as a parameter. Upon success, we will see the response data in the console.

DELETE request

DELETE request is often used to delete resources. You can use the delete method of the Axios instance to initiate a DELETE request. For example:

axiosInstance.delete('/users/1')
.then(response => console.log(response.data));
Copy after login

will send a DELETE request to https://api.example.com/users/1. Upon success, we will see the response data in the console.

It should be noted that all the above methods return Axios Promise. We can use .then() or .catch() to manage the success and failure of asynchronous requests.

Default configuration of Axios

When using Axios in a Vue application, we can manage our requests by creating an Axios instance and doing some configuration. The following are some common Axios configuration items:

baseURL: the root URL of the API
timeout: the request timeout (milliseconds)
headers: the default header of the request
withCredentials: whether to send cookies
validateStatus: Define which HTTP status codes should be considered successful status codes

We can use the Axios module level config to set the default configuration of Axios, for example:

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.timeout = 5000;
Copy after login

In this In the example, the Axios instance will use https://api.example.com as the root URL of the API and set the default request timeout to 5000 milliseconds.

Axios Interceptor

Axios interceptor is a powerful feature that can intercept and modify data during Axios requests and responses. We can use interceptors to inject certain default behaviors, such as injecting the Authorization header before making a request.

Axios interceptors are divided into request interceptors and response interceptors. The request interceptor handles the process of sending the request, while the response interceptor handles the data returned by the server.

In Axios, we can use the interceptors attribute to set interceptors. For each request and response, we can add each interceptor to interceptors. For example:

// 添加一个请求拦截器
axiosInstance.interceptors.request.use(config => {
    // 添加Authorization header
    config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
    return config;
}, error => Promise.reject(error));

// 添加一个响应拦截器
axiosInstance.interceptors.response.use(response => {
    // 如果响应是一个重定向到登录页面,我们就清空localStorage
    if (response.status === 302 && response.headers.location === '/login') {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
    }
    return response;
}, error => Promise.reject(error));
Copy after login

In this example, we added two interceptors, a request interceptor and a response interceptor. The request interceptor will add the Authorization header before each request is sent. The response interceptor will check whether the response is redirected to the login page, and if so, we clear the local access token and user information.

Error handling

Axios provides some methods to check for errors. In principle, we can catch Axios errors in .then() or .catch(). However, in a real production environment, we need better error handling. Axios errors can be caught and handled using interceptors. For example:

axiosInstance.interceptors.response.use(response => response, error => {
    // 处理错误
    if (error.response.status === 401) {
        // 如果响应状态码是401,我们就清空storage
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        // 跳转到登录界面
        router.push('/login');
    }
    return Promise.reject(error);
});
Copy after login

In this example, we add a response interceptor. If the response status code is 401, we will clear the token and user information in the local storage and jump to the login page.

in conclusion

Vue is a powerful front-end framework that uses Axios to implement asynchronous requests to APIs and data interaction in Vue applications. Axios is an easy-to-use HTTP library that handles a variety of HTTP methods and interceptors for handling asynchronous errors during requests and responses. We can use Axios to connect our Vue application to the backend API and enhance our Vue application with interceptors and error handling.

The above is the detailed content of How to use Axios to implement asynchronous requests and data interaction under Vue?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template