ホームページ  >  記事  >  ウェブフロントエンド  >  uniappにリクエストインターセプターを追加する方法

uniappにリクエストインターセプターを追加する方法

coldplay.xixi
coldplay.xixiオリジナル
2021-02-01 17:01:208912ブラウズ

Uniapp メソッドによるリクエスト インターセプターの追加: 1. LsxmRequest クラスを定義し、デフォルトの構成、インターセプター、およびリクエスト メソッドを追加します; 2. その後、構成をカスタマイズしてインターフェイス アドレスを取得し、get を追加する必要があります;3. シンボル機能を使用して 4 つのプライベート変数を定義し、変数の汚染を防ぎます。

uniappにリクエストインターセプターを追加する方法

このチュートリアルの動作環境: Windows7 システム、uni-app2.5.1 バージョン、DELL G3 コンピューターこの方法は、すべてのブランドのコンピューターに適しています。

Uniapp によるリクエスト インターセプターの追加方法:

1. 変数汚染を防ぐために、シンボル機能を使用して 4 つのプライベート変数を定義します。

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 を追加します。その後、構成をカスタマイズしてインターフェイス アドレスを取得する必要があります。クラスに 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 のリクエスト構成項目をインスタンス化してカスタマイズします (プロジェクトのニーズに応じてヘッダーにトークンを追加します) とインターセプター

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 Introduction で、API をマウントしますインターフェースを追加する必要がある場合は、apis.js にインターフェースを追加するだけで済みます (apis.js のインターフェースは、後で機能に応じて分割でき、モジュール管理)

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

8. この時点で、ページ上で

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

を使用すると、他の質の高い記事について詳しく知ることができます。

# に注意してください。 # #uni-appコラム~

以上がuniappにリクエストインターセプターを追加する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。