How to use Axios requests in Vue projects

Time:2021-12-8
catalogue
  • 1. Installation
  • 2. There are no problems with encapsulation
  • 3. Create file
  • 4. Request address configuration
  • 5. Axios configuration, setting request header and response code processing
  • 6. Use

In actual projects, data interaction with the background is indispensable. I usually use the Axios library, so the following examples are encapsulated based on Axios.

1. Installation

First, NPM installing Axios is simple: NPM install Axios

2. There are no problems with encapsulation

In projects without encapsulated interfaces, the following interface calling methods can be seen everywhere in the file:


this.$axios.post("/user/add", {
    params: {
        name: this.name,
        age: this.age
    }
})
.then(res => {
    console.log(res)
})
.then(err => {
    console.log(res)
})

This is not impossible, but there are some defects. The URL of the interface request is scattered in various files. If you need to do some processing when the interface call succeeds or fails, you need to change each file. Therefore, these interface requests are unified and centralized. If there is any adjustment, it is good to find and modify them directly in the centralized files instead of checking each file.

3. Create file

First, in the SRC directory of the project, create a new folder and file directory structure as follows:

Table of contents – SRC source code directory

│♪ API interface file directory

│ │♪ — Interface API of login.api.js login module

│ │ └ — Interface API of user.api.js user module

│♪ – directory of files related to services request

│ │♪ — address.js request address profile

│ │ └ – request.js Axios encapsulation, request interception, response code processing, etc

API interface file modules can be divided according to their actual projects, business functions, business logic or other forms.

4. Request address configuration

Generally, there will be more than one project environment, and less will also have development environment and production environment. Normally, there are different baseurls in the development environment and production mode, so we need to switch different baseurls according to different environments.

Address.js file:

//According to process.env.node_ Env switch between different baseurls
const isPro = process.env.NODE_ENV === 'production'
​
module.exports = {
    //'APIs': proxy set in vue.config.js
    baseURL: isPro ? 'http://192.168.100.120/ceds' : '/apis'
}

5. Axios configuration, setting request header and response code processing

The general idea is to encapsulate a request class, which contains request methods such as get and post. These request methods will call the request method, which calls the original Axios request through different parameters passed in, and then returns a promise.

Request.js file:

import axios from 'axios'
import Qs from 'qs'
import Vue from 'vue'
Import {gettoken} from '@ utils / session. Utils' // store the obtained token file
Import address from '. / address' // request address
​
class Request {
    constructor () {
        //Create an Axios instance
        this._axios = axios.create({
            baseURL: address.baseURL,
            Timeout: 1000 * 5, // request timeout
            headers: {}
        })
        //Request interception
        this._axios.interceptors.request.use(
            config => {
                const requestHeader = {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Content-Type': 'application/json; charset=UTF-8',
                    'Access-Control-Allow-Origin': '*',
                    Token: gettoken() // add tokens uniformly in the request header
                }
                config.headers = Object.assign(config.headers, requestHeader)
                return config
            },
            error => {
                Promise.reject(error)
            }
        )
    }
     
    //Judge whether the parameters are placed in query or body according to the request method.
    //The most intuitive difference is that, for example, the get request contains the parameters in the URL, while the post puts the parameters in the body through the request body, so the parameter forms are different when submitting
    //In the following four parameter forms of my common request methods, you can adjust them by yourself
    /**
      *Send get request
      *@ param {string} URL address
      *@ param {object} query query parameters
      *@ return JSON data
      */
    get (url, query = {}) {
        return this._request('get')(url, {
            ...query
        })
    }
    /**
      *Send post request
      *@ param {string} URL address
      *@ param {object} body query parameters
      *@ return JSON data
      */
    post(url, body = {}, headers) {
        let data;
        if(this.isFormData(body)) {
            data = body
        } else if(Array.isArray(body)) {
            data = body
        } else {
            data = { ...body }
        }
        return this._request('post')(url, headers)(url, data);
    }
    put (url, body = {}) {
        return this._request('put')(url, {
            ...body
        });
    }
    delete(url, body = {}) {
        return this._request('delete')(url, {
            ...body
        });
    }
​
    isFormData = v => {
        return Object.prototype.toString.call(v) === '[object FormData]'
    }
​
​
    /**
      *Set request header
      *@ param {object} header request header
      */
    setHeaders (header) {
        Object.keys(header).forEach(key => {
            this._axios.defaults.headers[key] = header[key]
        })
    }
​
    //Processing request headers
    handleHeaders () {
        const headers = {}
        headers['XMIME-TYPE'] = '3'
        Headers['Content-Type'] = 'application/json; charset=UTF-8'
        return headers
    }
​
    /**
      *Send request
      *@ param {string} method request method type
      * @param headers
      * @returns {function(*=, *=):Promise<unknown>}
      * @private
      */
    _request (method, headers) {
        This. Setheaders (this. Handleheaders()) // set unified request headers
        if (headers) {
            This. Setheaders (headers) // custom request headers
        }
         
        return (url, data, timeout) => {
            const config = {
                url,
                method,
                timeout: timeout || this._axios.defaults.timeout
            }// construct request config
​
            //Judge the request type get post
            const paramType = ['get', 'delete'].indexOf(method) !== -1 ? 'params' : 'data'
            config[paramType] = data
            //Parameter serialization
            config.paramsSerializer = params => {
                return Qs.stringify(params, { arrayFormat: 'repeat' });
            }
             
            return new Promise((resolve, reject) => {
                //Send the real request, verify the permission, check 404 and other status
                this._axios
                    .request(config)
                    .then(response => {
                        if (this.handleSuccessStatus(response.data.code, response.data)) {
                            if (response.headers['content-type'] !== 'text/plain; charset=urf-8') {
                            resolve(
                                    //Secondary packaging of response results
                                    Object.assign(
                                      {
                                           success: Number(response.data.code) === 200,
                                            data: response.data.data,
                                            msg: response.data.msg
                                        },
                                       response.data
                                    )
                                )// processing returned results
                            } else {
                                resolve(response.data)
                            }
                        }
                    }, response => {
                        //Processing error code
                      if(response.response) {
                            const statusCode = response.response.status
                            this.handleErrorStatus(statusCode)
                        } else {
                           Vue.prototype.$message.error(response.message)
                        }
                        reject(response)
                    })
                    .catch(err => {
                        reject(err)
                    })
                })
            }
        }
    }
​
    //The request is successful, and the error code is returned
    //The specific status code shall be unified with the background developers, and then the corresponding prompt shall be given according to the status code
    //The following is my operation in the project. You can adjust and expand it yourself
    handleSuccessStatus (code, data) {
        let result = ''
        let flag = false
        switch (code) {
            case '20007':
                Result = 'secondary authentication password not found!'
                flag = true
                break
            case '20008':
                Result = 'your secondary authentication password has not been modified, please modify it first!'
                flag = true
                break
            case '20009':
                Result = 'you haven't started secondary authentication, please contact the administrator!'
                flag = true
                break
            case '90001':
                Result = 'please enter the secondary authentication password!'
                flag = true
                break
            case '90002':
                Result = 'no operation permission!'
                flag = true
                break
            default:
                break
        }
​
        //Notify
        //The $message method is the prompt component in the element UI I introduced on demand. You can replace it with your own prompt component
        if (result) {
            Vue.prototype.$message.error(result)
        }
        return flag
    }
    //Get the error prompt according to the error code
    handleErrorStatus (statusCode) {
        let errorMsg = ''
        if (statusCode === 500) {
            Errormsg = 'data request failed, please contact administrator!'
        } else if (statusCode === 404) {
            Errormsg = 'request address error!'
        } else if (statusCode === 402) {
            Errormsg = 'you do not have permission to operate this data at present!'
        } else {
            Errormsg = 'request error!'
        }
        //Notify
        Vue.prototype.$message.error(errorMsg)
    }
}
​
export default new Request()

6. Use

In the interface management file, we can call the request class encapsulated above and pass in the corresponding parameters.

User.api.js file:

import http from '../services/request'
​
/**
 *@ description get user list
 *@ param {*} params parameters of the request interface
 */
//The requserlist method defined here will call the get method in our encapsulated request. The first parameter of the get method is the request address and the second parameter is the query parameter
export const reqUserList = params => http.get('/user/list', params)

In the called. Vue file, you can introduce the method and pass in the parameters

Import {requserlist} from '@ APIs / user. API' // import API
​
export default {
    name: 'UserList',
    ... ...
    created() {
     
    },
    methods: {
        async getUsers() {
            //Call the API interface and pass in parameters
            const res = await reqUserList({
                page: 1,
                size: 10
            })
            Console.log (RES) // get the response result
        }
    }
}

In this way, the encapsulation and basic use of the interface are completed.

PS: the above file names, folder names, method names and paths are all obtained by me. You can adjust them according to your own code style and habits.

The above is the details of how to use Axios requests in Vue projects. For more information about using Axios in Vue projects, please pay attention to other related articles of developeppaer!

Recommended Today

Heavyweight Tencent cloud open source industry’s first etcd one-stop governance platform kstone

​ Kstone open source At the kubecon China Conference held by CNCF cloud native foundation on December 9, 2021,Tencent cloud container tke team released the open source project of kstone etcd governance platform. KstoneIt was initiated by the TKE team of Tencent cloud containerCloud native one-stop etcd governance project based on kubernetes。 The project originates […]