How to use axios request in Vue project

How to use axios request in Vue project

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

1. Installation

The first step is to install axios with npm. It’s very simple: npm install axios

2. There is no problem with encapsulation

If there is no encapsulated interface in the project, you can see the following interface calling methods 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)
})

It is not impossible to write it this way, but there are some defects. The URLs of the interface requests 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. Therefore, these interface requests are centralized together. If there are any adjustments, you can directly find the changes in the centralized file without having to check each file again.

3. Create a file

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

├── src source code directory

│ ├── apis interface file directory

│ │ ├── login.api.js login module interface api

│ │ └── user.api.js User module interface api

│ ├── services request related file directory

│ │ ├── address.js request address configuration file

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

The division of API interface file modules can be based on your actual project, business function, business logic or other forms.

4. Request address configuration

Generally, we have multiple project environments, and at least one has a development environment and a 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:

// Switch different baseURLs according to process.env.NODE_ENV
const isPro = process.env.NODE_ENV === 'production'
​
module.exports = {
    // 'apis': proxy baseURL set by proxy in vue.config.js: 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 includes request methods such as get and post. These request methods will call the request method, which calls the original axios request through the 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 and obtain 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 token to the request header
                }
                config.headers = Object.assign(config.headers, requestHeader)
                return config
            },
            error => {
                Promise.reject(error)
            }
        )
    }
     
    // Based on the request method, determine whether the parameters should be placed in the query or body.
    // The most intuitive difference is that, for example, GET requests include parameters in the URL, while POST places parameters in the body through the request body, so the parameter formats when submitting are different // The following are the four parameter formats that I generally use for request methods, and you can adjust them yourself/**
      * Send a get request * @param {String} url address * @param {Object} query query parameter * @return json data */
    get (url, query = {}) {
        return this._request('get')(url, {
            ...query
        })
    }
    /**
      * Send post request * @param {String} url address * @param {Object} body query parameter * @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]
        })
    }
​
    // Process 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 a unified request header 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
​
            // Determine 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 actual request, verify permissions, 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 the response result Object.assign(
                                      {
                                          success: Number(response.data.code) === 200,
                                            data: response.data.data,
                                            msg: response.data.msg
                                        },
                                       response.data
                                    )
                                ) // Process the returned result } else {
                                resolve(response.data)
                            }
                        }
                    }, response => {
                        // Handle 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 is consistent with the backend developer, and then the corresponding prompt is given according to the status code // The following is my operation in the project, you can adjust and extend it by 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 changed, please change it first! '
                flag = true
                break
            case '20009':
                Result = 'You have not enabled 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
        }
​
        // Notify // The $message method is the prompt component in element-ui that 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 message based on the error code handleErrorStatus (statusCode) {
        let errorMsg = ''
        if (statusCode === 500) {
            errorMsg = 'Data request failed, please contact the administrator! '
        } else if (statusCode === 404) {
            errorMsg = 'Request address error! '
        } else if (statusCode === 402) {
            errorMsg = 'You currently do not have permission to operate this data! '
        } 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 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, introduce this 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, paths, etc. are all obtained by myself. You can adjust them according to your own coding style.

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 on 123WORDPRESS.COM!

You may also be interested in:
  • Use axios in vue project to upload pictures and other file operations
  • Detailed explanation of using axios in vue project
  • In the Vue project, use axios cross-domain processing
  • Sample code for axios request network interface encapsulation in vue project
  • Vue project practice elegant use of axios
  • Three minutes to quickly learn the basic usage of axios in vue projects (recommended!)

<<:  Detailed explanation of how to configure secondary domain name on Apache server under Linux environment

>>:  Detailed explanation of how to enable https service in Apache under Linux environment

Recommend

Detailed explanation of JavaScript's garbage collection mechanism

Table of contents Why do we need garbage collecti...

Summary of knowledge points on using calculated properties in Vue

Computed properties Sometimes we put too much log...

How to build mysql master-slave server on centos7 (graphic tutorial)

This article mainly introduces how to build a MyS...

mysql8 Common Table Expression CTE usage example analysis

This article uses an example to describe how to u...

Will Update in a Mysql transaction lock the table?

Two cases: 1. With index 2. Without index Prerequ...

Analysis of MySQL example DTID master-slave principle

Table of contents 1. Basic Concepts of GTID 2. GT...

MySQL 5.6.36 Windows x64 version installation tutorial detailed

1. Target environment Windows 7 64-bit 2. Materia...

Detailed tutorial on installing Tomcat8.5 in Centos8.2 cloud server environment

Before installing Tomcat, install the JDK environ...

ES6 loop and iterable object examples

This article will examine the ES6 for ... of loop...

Explanation of the working principle and usage of redux

Table of contents 1. What is redux? 2. The princi...

Embed player in web page embed element autostart false invalid

Recently, I encountered the need to embed a player...

React+Amap obtains latitude and longitude in real time and locates the address

Table of contents 1. Initialize the map 2. Map Po...

How webpack implements static resource caching

Table of contents introduction Distinguish betwee...