Analyze how uniapp dynamically obtains the interface domain name

Analyze how uniapp dynamically obtains the interface domain name

background

The interface domain name is not hard-coded but obtained dynamically. The specific implementation is to set the real interface domain name by reading a static json file. The advantage is that the original domain name may be blocked, so you can directly modify the configuration file in the background; otherwise, the h5 project may be okay, but the app must be re-released.

Code

// httpService.js encapsulates uni.request.

At the data request entrance, the domain name is obtained first, that is, the config.requestRemoteIp method is executed

import config from '@/config'
import Vue from 'vue'
import cacheData from '@/service/cacheData.js'
const MockUtil = () => import('@/libs/mockUtil.js')
import Storage from '@/libs/storage.js'

class HttpRequest {

    /**
     * Read interface data * @param options request information * @param noMock When using mock data as a whole, you can set a separate interface to request real data * @param cacheId
     * @returns {*}
     */
    async requestResolve(options, urlCustom = '', noMock = false, cacheId = null) {
        let remoteIP = await config.requestRemoteIp(); // Dynamically set the interface request domain name 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: 'Server error:' + 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)
            );
        })
    }

    /**
     *Mock data is imported on demand* @param options
     * @returns {*}
     */
    async getMockData(options) {
        const Mock = 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 test// 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

The above is the detailed analysis of how uniapp dynamically obtains the interface domain name. For more information about uniapp dynamically obtaining the interface domain name, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • uniapp project optimization methods and suggestions
  • How to develop uniapp using vscode
  • The complete code of the uniapp packaged applet radar chart component
  • How to use ECharts in WeChat Mini Programs using uniapp
  • uniapp dynamic modification of element node style detailed explanation

<<:  In-depth explanation of SQL statement execution (MySQL architecture overview -> query execution process -> SQL parsing order)

>>:  Zabbix monitoring solution - the latest official version 4.4 [recommended]

Recommend

Implementation of CSS child element selection parent element

Usually a CSS selector selects from top to bottom...

CSS element hiding principle and display:none and visibility:hidden

1. CSS element hiding <br />In CSS, there ar...

Linux file management command example analysis [display, view, statistics, etc.]

This article describes the Linux file management ...

MySQL 5.7.17 installation and configuration graphic tutorial

Features of MySQL: MySQL is a relational database...

How to improve Idea startup speed and solve Tomcat log garbled characters

Table of contents Preface Idea startup speed Tomc...

How to create a file system in a Linux partition or logical volume

Preface Learn to create a file system on your sys...

How to submit the value of a disabled form field in a form Example code

If a form field in a form is set to disabled, the ...

Can asynchrony in JavaScript save await?

I knew before that to synchronously obtain the re...

Sample code for automatic web page refresh and automatic jump

Automatic web page refresh: Add the following code...

How much data can be stored in a MySQL table?

Programmers must deal with MySQL a lot, and it ca...

MySQL query example explanation through instantiated object parameters

This article will introduce how to query data in ...

Develop a vue component that encapsulates iframe

Table of contents 1. Component Introduction 2. Co...

Native JS to achieve cool paging effect

This article uses an example to share with you a ...