Home > Web Front-end > Vue.js > Introduction to Axios encapsulation and common methods in Vue

Introduction to Axios encapsulation and common methods in Vue

WBOY
Release: 2023-06-09 16:13:06
Original
6230 people have browsed it

Introduction to Axios encapsulation and common methods in Vue

Axios is an HTTP library based on Promise. Its advantage is that it has good readability, ease of use and scalability. As a popular front-end framework, Vue also provides full support for Axios. This article will introduce how to encapsulate Axios in Vue, and introduce some commonly used methods of Axios.

1. Axios Encapsulation

During the development process, we often need to perform some customized encapsulation of Axios, such as adding fixed headers, unified processing of error returns, etc. This makes the code cleaner and easier to maintain. The following describes how to encapsulate Axios.

(1) Encapsulating request configuration

Let’s first define a config.js file to uniformly manage request configuration.

import axios from 'axios'

// 创建一个axios的实例
const Axios = axios.create({
  baseURL: '',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// 添加请求拦截
Axios.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    return config
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
Axios.interceptors.response.use(
  response => {
    // 对响应数据做些什么
    return response
  },
  error => {
    // 对响应错误做些什么
    return Promise.reject(error)
  }
)

export default Axios
Copy after login

In this file, we define an Axios instance and add request interception and response interceptor. In this way, when sending a request, it will first be processed by the request interceptor, and when responding, it will also be processed by the response interceptor first.

(2) Encapsulation request method

The Axios instance has been defined in the config.js file, and we can create different request methods as needed. For example, we now need to define a get method.

import Axios from './config'

export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    Axios.get(url, {
        params: params
      })
      .then(response => {
        resolve(response.data)
      })
      .catch(error => {
        reject(error)
      })
  })
}
Copy after login

The get method here uses the get method of the Axios instance, and passes in the url and params when requesting, so that a GET request can be sent. When the request is successful, we use Promise to resolve the returned data, and when the request fails, we reject the error.

Similarly, we can encapsulate different types of request methods as needed.

2. Introduction to common methods of Axios

After completing the encapsulation of Axios, the following will introduce some commonly used methods of Axios.

(1) GET request

get(url[, config])

url: The requested url can use a relative path or an absolute path.

config: Requested configuration, including params, headers, etc.

import Axios from './config'

Axios.get('/user?id=1')
  .then(response => {})
  .catch(error => {})
Copy after login

(2) POST request

post(url[, data[, config]])

url: The requested url can use a relative path or an absolute path.

data: Requested data.

config: Requested configuration, including headers, etc.

import Axios from './config'

Axios.post('/user', {
    id: 1,
    name: 'user'
  })
  .then(response => {})
  .catch(error => {})
Copy after login

(3) PUT request

put(url[, data[, config]])

url: The requested url can use a relative path or an absolute path.

data: Requested data.

config: Requested configuration, including headers, etc.

import Axios from './config'

Axios.put('/user', {
    id: 1,
    name: 'user'
  })
  .then(response => {})
  .catch(error => {})
Copy after login

(4) DELETE request

delete(url[, config])

url: The requested url can use a relative path or an absolute path.

config: Requested configuration, including headers, etc.

import Axios from './config'

Axios.delete('/user?id=1')
  .then(response => {})
  .catch(error => {})
Copy after login

(5) Request interception

In the config.js file, we define a request interceptor. You can use request interceptors to do some custom data processing, add request headers, etc.

Axios.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    config.headers.Authorization = 'token'
    return config
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)
Copy after login

(6) Response interception

In the config.js file, we define a response interceptor. You can use response interceptors to do some custom error handling, data processing, etc.

Axios.interceptors.response.use(
  response => {
    // 对响应数据做些什么
    return response
  },
  error => {
    // 对响应错误做些什么
    if (error.response) {
      // do something
    }
    return Promise.reject(error)
  }
)
Copy after login

3. Summary

This article introduces how to encapsulate Axios in Vue, as well as some commonly used methods of Axios. The advantage of Axios lies in its ease of use and scalability, which can help us quickly send HTTP requests and process response results during development. When using Axios, we should achieve unified request configuration management to facilitate later maintenance. At the same time, different types of request methods should be encapsulated as needed to meet various development needs.

The above is the detailed content of Introduction to Axios encapsulation and common methods in 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