uniapp 发起网络请求

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

const BASE_URL = 'http://xxx.com';

if (process.env.NODE_ENV === 'development') {

  // #ifdef H5
  Vue.prototype.apiUrl = '';
  // #endif

  // #ifdef MP-WEIXIN
  Vue.prototype.apiUrl = BASE_URL;
  // #endif


} else {
  Vue.prototype.apiUrl = BASE_URL;
}

function setDefaultObj(options) {

  // default show loading icon
  if (options.loading === undefined) {
    options.loading = true;
  }

  // default method is get
  if (!options.method) options.method = 'GET'

  // send formdata
  if (options.formData) {
    options.header = {
      ...options.header,
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }

  // deault data
  if (!options.data) options.data = {}

  // token data
  if (!options.data.token) {
    options.data.token = uni.getStorageSync('token') || '';
  }
}

Vue.prototype.request = function(options) {
  setDefaultObj(options);
  if (options.loading) {
    uni.showLoading({
      title: '加载中'
    });
  }
  const url = _join(this.apiUrl, options.url);

  if (options.filePath) {
    // 传文件
    // https://www.kancloud.cn/guobaoguo/uni-app/821793
    const uploadTask = uni.uploadFile({
      url: url,
      filePath: options.filePath,
      name: options.name,
      formData: options.data,
      header: options.header,
      success: res => {
        if (options.loading) uni.hideLoading();
        if (typeof options.success == "function") options.success(JSON.parse(res.data));
      },
      fail: res => {
        if (options.loading) uni.hideLoading();
        if (typeof options.fail == "function") options.fail({ ...res,
          data: JSON.parse(res.data)
        });
      }
    });
  } else {
    uni.request({
      url: url,
      data: options.data,
      method: options.method,
      header: options.header,
      success: res => {
        if (options.loading) uni.hideLoading();
        if (typeof options.success == "function") options.success(res.data);
      },
      fail: res => {
        if (options.loading) uni.hideLoading();
        if (typeof options.fail == "function") options.fail(res);
      }
    });

  }
}

Vue.prototype.postHttp = function(options) {
  this.request({
    ...options,
    method: 'POST',
    formData: true,
  });
}


function _join(a_url, b_url) {
  return a_url.replace(/\/+$/, "") + "/" + b_url.replace(/^\/+/, "")
}
  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 => {
        // ...
      }
    });

也可以看看:

posted @ 2020-05-30 12:58  Ajanuw  阅读(...)  评论(...编辑  收藏