uniapp使用类封装接口
大致分为三步
1 封装请求
2 定义接口
3 页面调用
1 在项目根目录下新建utils文件夹,该文件夹存放公共方法,新建http.js,内容入下
官方变量区分
// 区分环境 ,HbuilderX编辑运行时dev开发环境,发行后自动时生成环境
let baseUrl = ''
if (process.env.NODE_ENV === 'development') {
console.log('开发环境')
baseUrl = 'https://cnodejs.org/api/v1/';
} else {
console.log('生产环境')
baseUrl = 'https://cnodejs.org/api/v1/';
}
class Model {
//定义接口
api(opts = {}) {
//监听网络链接
uni.onNetworkStatusChange((res) => {
if (!res.isConnected) {
uni.showToast({
title: '网络连接不可用!',
icon: 'none'
});
}
return false
});
//定义参数对象
if (!opts.method) opts.method = 'get'
if (opts.domain) baseUrl = opts.domain
// token
let token = ''
// 鉴权
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'
}
// 删除鉴权
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社区接口
// 导入类
import Model from '@/utils/http.js'
// const baseUrl = 'https://cnodejs.org/api/v2'
//继承类的方法
class Cnode extends Model {
constructor(baseUrl) {
super(baseUrl)
this.baseUrl = baseUrl
}
//获取文章数据 //定义接口名
// get
getTopics(options) {
console.log(options);
options.url = `topics?page=${options.data.page}`
// 做本地自定义联合调试用
// 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 页面调用
<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请求,小伙伴们可自行测试,遇到问题的话可以从请求数据格式排查