• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

uni-app添加请求拦截器

武飞扬头像
PHP中文网
帮助139

uniapp添加请求拦截器的方法:

1、利用Symbol特性定义四个私有变量,防止变量污染

const config = Symbol('config')
const isCompleteURL = Symbol('isCompleteURL')
const requestBefore = Symbol('requestBefore')
const requestAfter = Symbol('requestAfter')

2、定义LsxmRequest类并添加默认配置、拦截器与请求方法

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)
    }
}

3、后续需要自定义config与获取接口地址,在类中添加get和set方法:

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

4、用自定义插件注册的方法将apis.js(后续在main.js中需要导入apis.js)中的接口赋到自定义的Vue原型变量$lsxmApi上,为了避免每个页面都要引入一次,在每个页面的beforeCreate生命周期混入。

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

5、在config.js中实例化并自定义请求配置项(此处根据项目需要在头部加入token)与拦截器

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

6、main.js中引入,将apis挂载到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()

7、需要添加接口时,只需在apis.js中添加接口即可(后续可将apis.js中的接口按照功能拆分,模块化管理)

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)
        }
        }
}

8、至此,页面中即可使用

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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanfebbj
系列文章
更多 icon
同类精品
更多 icon
继续加载