uniapp dynamic access domain interfaces

background

Interface domain not hard-coded, but dynamic acquisition. Specific implementation is by reading a static json file to set the actual interface domain. Because before all the company's projects are of such a deal, the benefits of the original domain name is likely to be sealed, so you can directly modify the background operation configuration files; otherwise, h5 project might better say, app, then must be re-issued version.

Code

// httpService.js the encapsulation of uni.request.

In the data request entrance Consolidated First acquire domain names that the implementation of the method config.requestRemoteIp

config Import from  ' @ / config ' 
Import Vue from  ' VUE ' 
Import cacheData from  ' @ /-Service / cacheData.js ' 
const MockUtil = () => Import ( ' @ / libs / mockUtil.js ' ) 
Import the Storage from  ' @ /libs/storage.js ' 

class the HttpRequest { 

    / * * 
     * data read interface 
     * @param options request information 
     * @param noMock in the case of using the entire mock data, an interface may be provided separately requested real data 
     * @param cacheId 
     @Returns {} * * 
     * / 
    the async requestResolve(options, urlCustom = '', noMock = false, cacheId = null) {
        let remoteIP = await config.requestRemoteIp(); // 动态设置接口请求域名
        
        if (process.env.NODE_ENV === 'development' && config.isMockApi && !noMock) {
            return this.getMockData(options)
        }
        if (cacheId && cacheData[cacheId]) {
            return this.testHttp(cacheData[cacheId])
        }
        return new Promise((resolve, reject) => {
            let baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro;
            options.url = baseUrl + options.url + `${urlCustom}`;
            uni.request(
                Object.assign({
                    success: (res) => {
                        if (res.statusCode != '200'){
                            uni.showToast({
                                title: '服务器错误:'+res.statusCode,
                                icon: "none"
                            })
                            reject()
                        }
                        else if (res.data.code == 10001) {
                            Storage.removeToken();
                            let vue = new Vue();
                            vue.$store.dispatch('logout')
                            vue.$routeUtil.reLaunch('main');
                        }
                        
                        else if (res.data.code != 200) {
                            if (res.data.message) {
                                uni.showToast({
                                    icon: 'none',
                                    title: res.data.message
                                });
                            }
                            reject(res.data)
                        } else {
                            if (cacheId) {
                                cacheData[cacheId] = res.data.data
                            }
                            Resolve (res.data.data) 
                        }
                    },
                    Fail: ERR => { 
                        uni.showToast ({ 
                            title: ' Server Error ' , 
                            icon: " none " 
                        }) 
                    } 
                }, Options) 
            ); 
        }) 
    } 

    / * * 
     * data according to the mock for an introduction 
     * @param Options 
     * @Returns {*} 
     * / 
    the async getMockData (Options) {
         const Mock = the await MockUtil ()
         const MockUrl = Mock.default[options.url]
        if (typeof MockUrl !== 'function') {
            return this.testHttp(MockUrl)
        }
        if (options.method === 'post') {
            return this.testHttp(MockUrl(options.data, false))
        }
        return this.testHttp(MockUrl(options.params, true))
    }
    testHttp(data) {
        let pro = new Promise(function(resolve, reject) {
            setTimeout(function() {
                resolve(data)
            }, 50)
        })
        return pro
    }
}
export default new HttpRequest()

// config.js

const config = {
  isMockApi: false,
  // requestUrl: 'http://qiniu.eightyin.cn/teacherpath.json?time=' + Math.random().toString(36),
  requestUrl: 'http://qiniu.eightyin.cn/teacherpathtest.json?time=' + Math.random().toString(36),
  baseUrl: {
     
    dev: '',
    pro: ''
  },
  img: {
    ossDomain: ''
  },
  uuid: Math.random().toString(36).substring(3, 20),
  requestRemoteIp: () => {
      console.log('config:', config)
      if (config.RemoteIpInited)
        return Promise.resolve();
        return new Promise((resolve, reject) => {
            uni.request({
                url: config.requestUrl,
                success: (response) => {
                    //todo 测试
                    // config.baseUrl.pro = response.data.data.path;
                    config.baseUrl.dev = 'http://bayin5.mycwgs.com/';
                    config.img.ossDomain = response.data.data.ossDomain;
                    config.RemoteIpInited = true;
                    resolve()
                },
                fail: () => {
                    config.RemoteIpInited = true;
                    resolve()
                }
            })
        });
  }
}

export default config

 

Guess you like

Origin www.cnblogs.com/fan-zha/p/11373118.html