Home > Web Front-end > uni-app > How to add request interceptor in uniapp

How to add request interceptor in uniapp

coldplay.xixi
Release: 2023-01-13 00:44:36
Original
9072 people have browsed it

Uniapp method to add a request interceptor: 1. Define the LsxmRequest class and add the default configuration, interceptor and request method; 2. Subsequently, you need to customize the config and obtain the interface address, and add get and set methods to the class. ;3. Use the Symbol feature to define four private variables to prevent variable pollution.

How to add request interceptor in uniapp

The operating environment of this tutorial: windows7 system, uni-app2.5.1 version, DELL G3 computer. This method is suitable for all brands of computers.

Uniapp's method of adding a request interceptor:

1. Use the Symbol feature to define four private variables to prevent variable pollution

const config = Symbol('config')
const isCompleteURL = Symbol('isCompleteURL')
const requestBefore = Symbol('requestBefore')
const requestAfter = Symbol('requestAfter')
Copy after login

2. Definition LsxmRequest class and add default configuration, interceptor and request method

class LsxmRequest {
    //默认配置
    [config] = {
        baseURL: '',
        header: {
            'content-type': 'application/json'
        },
        method: 'GET',
        dataType: 'json',
        responseType: 'text'
    }
    //拦截器
    interceptors = {
        request: (func) => {
            if (func) 
            {
                LsxmRequest[requestBefore] = func
            } 
            else 
            {
                LsxmRequest[requestBefore] = (request) => request
            }
        },
        response: (func) => {
            if (func) 
            {
                LsxmRequest[requestAfter] = func
            } 
            else 
            {
                LsxmRequest[requestAfter] = (response) => response
            }
        }
    }
    static [requestBefore] (config) {
        return config
    }
    static [requestAfter] (response) {
        return response
    }
    static [isCompleteURL] (url) {
        return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
    }
    
    request (options = {}) {
        options.baseURL = options.baseURL || this[config].baseURL
        options.dataType = options.dataType || this[config].dataType
        options.url = LsxmRequest[isCompleteURL](options.url) ? options.url : (options.baseURL + options.url)
        options.data = options.data
        options.header = {...options.header, ...this[config].header}
        options.method = options.method || this[config].method
        options = {...options, ...LsxmRequest[requestBefore](options)}
        return new Promise((resolve, reject) => {
            options.success = function (res) {
                resolve(LsxmRequest[requestAfter](res))
            }
            options.fail= function (err) {
                reject(LsxmRequest[requestAfter](err))
            }
            uni.request(options)
        })
    }
    get (url, data, options = {}) {
        options.url = url
        options.data = data
        options.method = 'GET'
        return this.request(options)
    }
    post (url, data, options = {}) {
        options.url = url
        options.data = data
        options.method = 'POST'
        return this.request(options)
    }
}
Copy after login

3. Subsequently, you need to customize the config and obtain the interface address. Add get and set methods in the class:

setConfig (func) {
        this[config] = func(this[config])
}
getConfig() {
    return this[config];
}
Copy after login

4. Use The custom plug-in registration method assigns the interface in apis.js (you need to import apis.js in main.js later) to the custom Vue prototype variable $lsxmApi. In order to avoid having to introduce it once on each page, in each page The beforeCreate life cycle of a page is mixed in.

LsxmRequest.install = function (Vue) {
    Vue.mixin({
        beforeCreate: function () 
        {
            if (this.$options.apis) 
            {
                console.log(this.$options.apis)
                Vue._lsxmRequest = this.$options.apis
            }
        }
    })
    
    Object.defineProperty(Vue.prototype, '$lsxmApi', {
        get: function () 
        {
            return Vue._lsxmRequest.apis
        }
    })
}
export default LsxmRequest
Copy after login

5. Instantiate and customize the request configuration items in config.js (add token in the header according to project needs) and interceptor

import LsxmRequest from './LsxmRequest'
const lsxmRequest = new LsxmRequest()
// 请求拦截器
lsxmRequest.interceptors.request((request) => {
    if (uni.getStorageSync('token')) {
        request.header['token'] = uni.getStorageSync('token');
    }
    return request
})
// 响应拦截器
lsxmRequest.interceptors.response((response) => {
    console.log('beforeRespone',response);
    // 超时重新登录
    if(response.data.isOverTime){
    uni.showModal({
            title:'提示',
            content:'您已超时,请重新登录!',
            showCancel:false,
            icon:'success',
            success:function(e){
                if(e.confirm){
                    uni.redirectTo({
                        url: '/pages/login/login'
                    })
                }
            }
        }); 
    }
    else
    {
        return response;
    }
})
// 设置默认配置
lsxmRequest.setConfig((config) => {
    config.baseURL = 'http://xxxxx.com'
    
    if (uni.getStorageSync('token')) {
        config.header['token'] = uni.getStorageSync('token');
    }
    return config;
})
export default lsxmRequest
Copy after login

6. In main.js Introduction, mount apis to Vue

import LsxmRequest from './service/LsxmRequest.js'
import apis from './service/apis.js'
import lsxmRequest from './service/config.js'
Vue.use(LsxmRequest)
Vue.prototype.baseDomain = lsxmRequest.getConfig().baseURL
App.mpType = 'app'
const app = new Vue({
    store,
    apis,
    ...App
})
app.$mount()
Copy after login

7. When you need to add an interface, you only need to add the interface in apis.js (the interface in apis.js can be split according to functions later, and the module Management)

import lsxmRequest from './config.js'
export default{
  apis:{
        //获取验证用户令牌
        getLoginToken(data){
            return lsxmRequest.post('/xxx/xxx/getLoginToken', data)
        },
        //登录
        login(data){
            return lsxmRequest.post('/xxx/xxx/login', data)
        }
        }
}
Copy after login

8. At this point, you can use

this.$lsxmApi.getLoginToken({}).then((resToken) => {
        console.log(resToken)
}
Copy after login

on the page to learn more about other high-quality articles, please pay attention touni-appColumn~

The above is the detailed content of How to add request interceptor in uniapp. 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