uniapp使用類封裝接口
大致分為三步
1 封裝請求
2 定義接口
3 頁面調(diào)用
1 在項目根目錄下新建utils文件夾因块,該文件夾存放公共方法,新建http.js灿里,內(nèi)容入下
官方變量區(qū)分
// 區(qū)分環(huán)境 ,HbuilderX編輯運行時dev開發(fā)環(huán)境垄懂,發(fā)行后自動時生成環(huán)境
let baseUrl = ''
if (process.env.NODE_ENV === 'development') {
console.log('開發(fā)環(huán)境')
baseUrl = 'https://cnodejs.org/api/v1/';
} else {
console.log('生產(chǎn)環(huán)境')
baseUrl = 'https://cnodejs.org/api/v1/';
}
class Model {
//定義接口
api(opts = {}) {
//監(jiān)聽網(wǎng)絡(luò)鏈接
uni.onNetworkStatusChange((res) => {
if (!res.isConnected) {
uni.showToast({
title: '網(wǎng)絡(luò)連接不可用!',
icon: 'none'
});
}
return false
});
//定義參數(shù)對象
if (!opts.method) opts.method = 'get'
if (opts.domain) baseUrl = opts.domain
// token
let token = ''
// 鑒權(quán)
let authorize = ''
if (uni.getStorageSync('token')) token = uni.getStorageSync('token')
if (uni.getStorageSync('Authorization')) authorize = uni.getStorageSync('Authorization')
// 前端自定義token失效
// if (token == '' || token == undefined || token == null) {
// uni.showToast({
// title: '賬號已過期匾浪,請重新登錄',
// icon: 'none',
// complete: function() {
// uni.reLaunch({
// url: '/pages/login/index'
// });
// }
// });
// }
let header = {
Authorization: authorize,
'Content-Type': 'application/json; charset=UTF-8'
}
// 刪除鑒權(quán)
if (opts.noAuth) {
delete header.Authorization
}
return new Promise((resolve, reject) => {
uni.request({
url: baseUrl + opts.url,
data: opts.data,
method: opts.method,
header: header,
success: res => {
if (res.statusCode === 200) {
if (res.data) {
resolve(res.data);
// token過期
} else if (res.data.returnCode === '401') {
uni.showModal({
title: '提示',
content: '登錄過期,請重新登錄',
success: function(res) {
if (res.confirm) {
uni.redirectTo({
url: '/pages/login/index'
});
uni.clearStorageSync();
} else if (res.cancel) {
uni.switchTab({
url: '/pages/work/index'
});
}
}
});
resolve(res.data);
} else {
uni.showToast({
title: res.data.returnMessage,
icon: 'none',
duration: 1500
});
reject(res.data);
}
}
},
fail: () => {
console.log('請求失敗,請稍候重試');
uni.hideLoading();
uni.showToast({
title: 'net error!',
icon: 'none',
duration: 1500
});
}
});
})
}
get(options = {}) {
options.method = 'GET'
return this.api(options)
}
post(options = {}) {
options.method = 'POST'
return this.api(options)
}
put(options = {}) {
options.method = 'PUT'
return this.api(options)
}
delete(options = {}) {
options.method = 'DELETE'
return this.api(options)
}
}
export default Model
2 根目錄新建model文件夾卷哩,用來存放接口蛋辈,新建接口文件,我這邊測試用cnode社區(qū)接口
// 導(dǎo)入類
import Model from '@/utils/http.js'
// const baseUrl = 'https://cnodejs.org/api/v2'
//繼承類的方法
class Cnode extends Model {
constructor(baseUrl) {
super(baseUrl)
this.baseUrl = baseUrl
}
//獲取文章數(shù)據(jù) //定義接口名
// get
getTopics(options) {
console.log(options);
options.url = `topics?page=${options.data.page}`
// 做本地自定義聯(lián)合調(diào)試用
// options.domain = `http:172.168.0.0.1:8080/`
return this.get(options)
}
// post
postxxx (options) {
options.url = '/api/xxx'
return this.post(options)
}
}
const cnodeModel = new Cnode()
export default cnodeModel
3 頁面調(diào)用
<script>
import cnodeModel from '@/model/cnode.js';
console.log(cnodeModel);
export default {
data() {
return {
params: {
page: 1
}
};
},
onLoad() {},
onShow() {
this.getTopics();
},
methods: {
getTopics() {
let opts = {
data: { page: 1 }
};
cnodeModel.getTopics(opts).then(res => {
console.log(res);
});
}
}
};
</script>
目前沒有測試post請求将谊,小伙伴們可自行測試冷溶,遇到問題的話可以從請求數(shù)據(jù)格式排查