- 创建
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();
}
});
}
- 在
main.js
中导入
import ‘./http-config‘;
-
manifest.json
配置代理
{
...
"h5": {
"router": {
"mode": "hash"
},
"devServer": {
"https": false,
"proxy": {
"/api": {
"target": "http://xxx.com",
"changeOrigin": true,
"secure": false,
"pathRewrite": {
"^/api": "/"
}
}
}
}
}
}
- 使用
// http://xxx.com/getvideo
this.request({
url: ‘/getvideo‘,
success: res => {
// ...
}
});
也可以看看: