uniapp請求介面封裝
先上截圖,再上程式碼
1、截圖
2、程式碼
base.js
class Base {
constructor() {
this.baseRestUrl = '伺服器地址';
}
request(params, auth = true) {
var that = this;
var url = this.baseRestUrl + params.url;
let file = params.file; // 是否為上傳
var loading = params.loading == "hide" ? "hide" : "show";
if (!params.type) {
params.type = 'get';
}
/*不需要再次組裝地址*/
if (params.setUpUrl == false) {
url = params.url;
}
if (file === undefined) {
wx.request({
url: url,
data: params.data,
method: params.type,
header: {
'content-type': 'application/json'
},
success: function (res) {
var code = res.statusCode.toString();
var startChar = code.charAt(0);
if (startChar == '2') {
params.sCallback && params.sCallback(res.data);
} else {
that._processError(res);
params.eCallback && params.eCallback(res.data);
}
},
complete: function (res) {
// loading == "show" ? wx.hideLoading() : false;
},
fail: function (err) {
that._processError(err);
}
});
}
// 發起上傳
if (file) {
return new Promise(function (resolve, reject) {
wx.uploadFile({
url: url,
header: {"Content-Type": "multipart/form-data" },
name: 'file',
filePath: file,
formData: data,
success: function(res) {
resolve(JSON.parse(res.data));
loading == "show" ? wx.hideLoading() : false;
},
fail: function (err) {
loading == "show" ? wx.hideLoading() : false;
reject(err);
}
})
});
}
}
// 列印錯誤資訊
_processError(err) {
console.log(err);
}
};
export { Base };
api.js
import {
Base
} from './base.js';
let urlList = {
setMobile: 'Index/setMobile', // 獲取手機號
}
class Api extends Base {
setMobile(param, callback) {
var param = {
url: urlList.setMobile,
type: "get",
data: param,
sCallback: function(data) {
callback && callback(data);
}
};
this.request(param);
}
}
export {
Api
};
main.js
import App from './App'
import {Api} from 'pages/api/api.js'
Vue.prototype.api = new Api()
// #ifndef VUE3
import Vue from 'vue'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
// #endif
// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
const app = createSSRApp(App)
return {
app
}
}
// #endif
index.vue
<template>
<view class="content">
</view>
</template>
<script>
export default {
data() {
return {
}
},
onLoad() {
//介面請求
this.api.setMobile({
欄位名:值,
欄位名:值,
欄位名:值
},res=>{
//把返回結果列印一下
console.log(res)
})
},
methods: {
}
}
</script>
<style>
</style>