uniapp 发起网络请求

  1. 创建http-config.js
import Vue from ‘vue‘


if (process.env.NODE_ENV === ‘development‘) {
  Vue.prototype.apiUrl = ‘/api‘;
} else {
  Vue.prototype.apiUrl = ‘http://xxx.com‘;
}

function setDefaultObj(obj) {
  if (obj.loading === undefined) {
    obj.loading = true;
  }
  if (!obj.method) obj.method = ‘GET‘
}

Vue.prototype.request = function(obj) {
  setDefaultObj(obj);
  if (obj.loading) {
    uni.showLoading({
      title: ‘加载中‘
    });
  }
  uni.request({
    url: this.apiUrl + obj.url,
    data: obj.data,
    method: obj.method,
    header: obj.header,
    success: res => {
      if (typeof obj.success == "function") obj.success(res);
      if (obj.loading) uni.hideLoading();
    },
    fail: res => {
      if (typeof obj.success == "function") obj.fail(res);
      if (obj.loading) uni.hideLoading();
    }
  });
}
  1. main.js中导入
import ‘./http-config‘;
  1. manifest.json配置代理
{
  ...

  "h5": {
    "router": {
      "mode": "hash"
    },
    "devServer": {
      "https": false,
      "proxy": {
        "/api": {
          "target": "http://xxx.com",
          "changeOrigin": true,
          "secure": false,
          "pathRewrite": {
            "^/api": "/"
          }
        }
      }
    }
  }

}
  1. 使用
    // http://xxx.com/getvideo
    this.request({
      url: ‘/getvideo‘,
      success: res => {
        // ...
      }
    });

也可以看看:

uniapp 发起网络请求

上一篇:Windows10下Vmware15.5虚拟机安装苹果的10.15.5(19F96)CDR镜像


下一篇:后端与移动端联调测试逆天神器之FLEX