vue3 [use axios and encapsulate axios request]

Step 1: Install axios

npm install axios

Step 2: Write the request file

New request.js

Simple axios package, inside the relevant prompt information, you can introduce element-plus to add

/**axios封装
 * 请求拦截、相应拦截、错误统一处理
 */
import axios from 'axios';
import QS from 'qs';
import router from '../router/index'
//qs.stringify()是将对象 序列化成URL的形式,以&进行拼接
//  let protocol = window.location.protocol; //协议
//  let host = window.location.host; //主机
//  axios.defaults.baseURL = protocol + "//" + host;
axios.defaults.baseURL = '/api'

axios.interceptors.request.use( //响应拦截
    async config => {
        // 每次发送请求之前判断vuex中是否存在token        
        // 如果存在,则统一在http请求的header都加上token,这样后台根据token判断你的登录情况
        // 即使本地存在token,也有可能token是过期的,所以在响应拦截器中要对返回状态进行判断 
        config.headers.token = sessionStorage.getItem('token')
        return config;
    },
    error => {
        return Promise.error(error);
    })
// 响应拦截器
axios.interceptors.response.use(
    response => {
        if (response.status === 200) {
            return Promise.resolve(response); //进行中        
        } else {
            return Promise.reject(response); //失败       
        }
    },
    // 服务器状态码不是200的情况    
    error => {
        if (error.response.status) {
            switch (error.response.status) {
                // 401: 未登录                
                // 未登录则跳转登录页面,并携带当前页面的路径                
                // 在登录成功后返回当前页面,这一步需要在登录页操作。                
                case 401:
                    break
                // 403 token过期                
                // 登录过期对用户进行提示                
                // 清除本地token和清空vuex中token对象                
                // 跳转登录页面                
                case 403:
                    sessionStorage.clear()
                    router.push('/login')
                    break
                // 404请求不存在                
                case 404:
                    break;
                // 其他错误,直接抛出错误提示                
                default:
            }
            return Promise.reject(error.response);
        }
    }
);
/** 
 * get方法,对应get请求 
 * @param {String} url [请求的url地址] 
 * @param {Object} params [请求时携带的参数] 
 */
const $get = (url, params) => {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params,
        })
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}
/** 
 * post方法,对应post请求 
 * @param {String} url [请求的url地址] 
 * @param {Object} params [请求时携带的参数] 
 */
const $post = (url, params) => {
    return new Promise((resolve, reject) => {
        axios.post(url, QS.stringify(params)) //是将对象 序列化成URL的形式,以&进行拼接   
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}
//下面是将get和post方法挂载到vue原型上供全局使用、
// vue2.x中是通 Vue.prototype 来绑定的,像这样Vue.prototype.$toast = Toast。在vue3中取消了Vue.prototype,推荐使用globalProperties来绑定,
export default {
    install: (app) => {
        app.config.globalProperties['$get'] = $get;
        app.config.globalProperties['$post'] = $post;
        app.config.globalProperties['$axios'] = axios;
    }
}

A few points to note:

  • 1. We can obtain the protocol and host ip port through window.location.protocol and window.location.host, and then uniformly set the default request baseURL of axios
//  let protocol = window.location.protocol; //协议
//  let host = window.location.host; //主机
//  axios.defaults.baseURL = protocol + "//" + host;
  • 2. qs.stringify() is to serialize the object into the form of URL, splicing with & 

(1) First introduce the qs module

import QS from 'qs';

(2) Wrap and use in front of the request parameters

 (3) View the parameter results, it is converted to the formdata parameter transfer form, which is convenient, fast and

  • 3. Global mounting, in vue2.x, it is bound through Vue.prototype , for example, Vue.prototype.$toast = Toast. Vue.prototype is canceled in vue3, it is recommended to use globalProperties to bind and mount to the proxy of the component
export default {
    install: (app) => {
        app.config.globalProperties['$get'] = $get;
        app.config.globalProperties['$post'] = $post;
        app.config.globalProperties['$axios'] = axios;
    }
}

 Step 3: Introduce in main.js

Note: axios has been introduced globally in request.js, and there is no need to introduce axios in main.js, otherwise an error will be reported

 Step 4: Use in components

introduce

 Since in Vue3, the component instance cannot be obtained through this in the setup, the value printed by console.log(this) is undefined. So we need to get the current component instance through the getCurrentInstance method.

Note: getCurrentInstance can only be used in setup or lifecycle hooks .  

Proxy is an attribute in the getCurrentInstance() object, and then the proxy is obtained by deconstructing and assigning the object. 

import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance();

Then get the mounted get and post requests through the proxy.

function testFunc() {
    let data = {
        roleId: "A",
        username: "dpc",
        password: "--",
        sysType: "zhfw",
    }
    proxy.$post("/index/login", data).then((response) => {
        console.log(response)
    })
}

Guess you like

Origin blog.csdn.net/qq_41579104/article/details/130627226