SoFunction
Updated on 2025-04-12

How to use axios request in a Vue project

In actual projects, data interaction with the background is indispensable. I usually use the axios library, so the following example is also encapsulated based on axios.

1. Installation

First of all, npm install axios is very simple: npm install axios

2. Problems with no encapsulation

If you don't have an encapsulated interface, you can see the following interface call methods everywhere in the file:

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

This is not impossible to write, but there are some flaws. The urls requested by the interface are scattered in various files. If you need to do some processing when the interface call succeeds or fails, you need to change each file. So, if there is any adjustment, just find the modification in the centralized file without checking each file.

3. Create a file

First, in the project's src directory, create a new folder and file directory structure as follows:

├── src source code directory

│ ├── apis interface file directory

│ │ ├── The interface api of the login module

│ │ └── Interface API of user module

│ ├── services Request related file directory

│ │ ├── Request address configuration file

│ │ └── axios encapsulation, request interception, response code processing and other operations

The division of API interface file modules can be divided according to your actual projects, business functions, business logic or other forms.

4. Request address configuration

Generally, our project environment will have multiple projects, and fewer ones will also have a development environment and a production environment. Under normal circumstances, there are different baseURLs in the development environment and production mode, so we need to switch different baseURLs according to different environments.

document:

// Switch different baseURLs according to .NODE_ENVconst isPro = .NODE_ENV === 'production'
​
 = {
    // 'apis': proxy settings in proxy    baseURL: isPro ? 'http://192.168.100.120/ceds' : '/apis'
}

5. Axios configuration, set 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. This method calls the original axios request through different parameters passed in, and then returns a promise.

document:

import axios from 'axios'
import Qs from 'qs'
import Vue from 'vue'
import { getToken } from '@Utils/' //Storage token fileimport address from './address' // Request address​
class Request {
    constructor () {
        // Create an axios instance        this._axios = ({
            baseURL: ,
            timeout: 1000 * 5, // Request timeout            headers: {}
        })
        // Request for interception        this._axios.(
            config => {
                const requestHeader = {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Content-Type': 'application/json; charset=UTF-8',
                    'Access-Control-Allow-Origin': '*',
                    token: getToken() // Add tokens to the request header uniformly                }
                 = (, requestHeader)
                return config
            },
            error => {
                (error)
            }
        )
    }
     
    // According to the request method, determine whether the parameters are placed in the query or body.    // The most intuitive difference, such as GET requests to include parameters in the url, while POST places parameters in the body through the request body, so there are differences in the parameter form when submitting    // The following are four parameter forms that I usually use for request methods, you can adjust them yourself    /**
       * Send a 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((body)) {
            data = body
        } else if((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 (v) === '[object FormData]'
    }
​
​
    /**
       * Set request header
       * @param {Object} header request header
       */
    setHeaders (header) {
        (header).forEach(key => {
            this._axios.[key] = header[key]
        })
    }
​
    // Processing request headers    handleHeaders () {
        const headers = {}
        headers['XMIME-TYPE'] = '3'
        Headers['Content-Type'] = 'application/json; charset=UTF-8'
        return headers
    }
​
    /**
       * Send a request
       * @param {String} method Request method type
       * @param headers
       * @returns {function(*=, *=):Promise<unknown>}
       * @private
       */
    _request (method, headers) {
        (()) // Set a unified request header        if (headers) {
            (headers) // Custom request header        }
         
        return (url, data, timeout) =&gt; {
            const config = {
                url,
                method,
                timeout: timeout || this._axios.
            } // Construct request config​
            // Determine the request type get post            const paramType = ['get', 'delete'].indexOf(method) !== -1 ? 'params' : 'data'
            config[paramType] = data
            // Parameter serialization             = params =&gt; {
                return (params, { arrayFormat: 'repeat' });
            }
             
            return new Promise((resolve, reject) =&gt; {
                // Send real request, verify permissions, check 404 and other status                this._axios
                    .request(config)
                    .then(response =&gt; {
                        if ((, )) {
                            if (['content-type'] !== 'text/plain; charset=urf-8') {
                      resolve(
                                    // Secondary packaging for response results                                    (
                                    {
                                         success: Number() === 200,
                                            data: ,
                                            msg: 
                                        },
                                       
                                    )
                                ) // Processing returns the result                            } else {
                                resolve()
                            }
                        }
                    }, response =&gt; {
                        // Handle error code                    if() {
                            const statusCode = 
                            (statusCode)
                        } else {
                         .$()
                        }
                        reject(response)
                    })
                    .catch(err =&gt; {
                        reject(err)
                    })
                })
            }
        }
    }
​
    // The request is successful and the error code is returned    // The specific status code is unified with the background developer, and then the corresponding prompts are made according to the status code    // Below 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 = 'The secondary authentication password was not found!  '
                flag = true
                break
            case '20008':
                result = 'Your secondary authentication password has not been modified yet, please modify it first!  '
                flag = true
                break
            case '20009':
                result = 'You have not enabled the secondary authentication yet, 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
        }
​
        // Make notification        // The $message method is the prompt component in element-ui I introduced on demand, you can replace it with your own prompt component        if (result) {
            .$(result)
        }
        return flag
    }
    // Get error prompts based on error code    handleErrorStatus (statusCode) {
        let errorMsg = ''
        if (statusCode === 500) {
            errorMsg = 'The data request failed, please contact the administrator!  '
        } else if (statusCode === 404) {
            errorMsg = 'The request address is wrong!  '
        } else if (statusCode === 402) {
            errorMsg = 'You do not currently have permission to operate this data!  '
        } else {
            errorMsg = 'There was an error in the request!  '
        }
        // Make notification        .$(errorMsg)
    }
}
​
export default new Request() 

6. Use

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

document:

import http from '../services/request'
​
/**
  * @description Get user list
  * @param {*} params Request the parameters of the 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 parameterexport const reqUserList = params =&gt; ('/user/list', params) 

In the called .vue file, introduce this method and pass in the parameters

import { reqUserList } from '@Apis/' // 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
            })
            (res) // Response results obtained        }
    }
}

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

PS: I have obtained the above file names, folder names, method names, paths, etc. myself. You can adjust them according to your own code style and habits.

The above is the detailed content of how to use axios request in Vue project. For more information about using axios in Vue project, please follow my other related articles!