微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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 => {
        // ...
      }
    });

也可以看看:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐