uniapp 发起网络请求

时间:2020-05-30
本文章向大家介绍uniapp 发起网络请求,主要包括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 => {
        // ...
      }
    });

也可以看看:

原文地址:https://www.cnblogs.com/ajanuw/p/12992084.html