全局注册,通过this调用
适用于vue 跟 uniapp
在uniapp 下
跟pages同级下
创建一个api文件夹下
在创建一个http.js
1.http.js
//服务器地址
const service = "域名/ip地址";
module.exports = (params) => {
let url = params.url;
let method = params.method;
let header = params.header || {};
let data = params.data || {};
// 请求方式 GET POST
if (method) {
method = method.toUpperCase(); // 小写转大写
if (method == "POST") {
header = {
"content-type": "application/x-www-form-urlencoded"
}
}
}
// 发起请求 加载动画
if (!params.hideLoading) {
uni.showLoading({
title: "加载中"
})
}
// 发起网络请求
uni.request({
url: service + url,
method: method || "GET",
header: header,
data: data,
dataType: "json",
sslVerify: false, // 是否验证ssl证书
success: res => {
console.log(res)
if (res.data.code && res.data.code != 200) {
// api错误
uni.showToast({
title:res.data.info,
icon:'none'
})
return;
}
typeof params.success == "function" && params.success(res.data);
},
fail: err => {
uni.showToast({
title:res.data.info,
icon:'none'
})
typeof params.fail == "function" && params.fail(err.data);
},
complete: (e) => {
console.log("请求完成");
uni.hideLoading()
typeof params.complete == "function" && params.complete(e.data);
return;
}
})
}
2:在main.js注册全局
main.js文件
import Vue from 'vue'
import App from './App'
import http from './api/http.js'
const msg = (title, duration=1500, mask=false, icon='none')=>{
//统一提示方便全局修改
if(Boolean(title) === false){
return;
}
uni.showToast({
title,
duration,
mask,
icon
});
}
Vue.config.productionTip = false
Vue.prototype.http = http
Vue.prototype.$api = {msg};
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
3:调用接口
onLoad() {
this.http({
url:'域名/ip地址',
method:'GET',
success: res => {
console.log(res)
},
fail: err => {
console.log(res)
}
})
},