首页 > 移动平台 > 详细

uniapp 发起网络请求

时间:2020-05-30 14:23:13      阅读:103      评论:0      收藏:0      [点我收藏+]
  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 发起网络请求

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!