const api_base_url = 'https://***';
// 错误提示
const tips = {
1: '抱歉,出现了一个未知错误'
};
class HTTP {
// 网络请求函数
request(params) {
if (!params.method) {
params.method = 'GET'
}
wx.request({
url: api_base_url + params.url,
method: params.method,
data: params.data,
dataType:'json',
header: {
'content-Type': 'application/x-www-form-urlencoded',
'accessToken': wx.getStorageSync('token') || ''
},
success: (res) => {
let code = res.statusCode.toString()
// 判断状态码是否以2开头
if (code.startsWith('2') && res.data.code === 200) {
wx.hideLoading();
// 回调函数
params.success(res.data)
} else {
this._show_error(res.data)
}
},
fail: (err) => {
this._show_error(1)
}
})
}
// 错误处理函数
_show_error(res) {
console.log(res)
let msg = ''
if (res.code !== 500 || !res.msg) {
var error_code = 1
msg = tips[error_code]
}else{
msg = res.msg
}
wx.showToast({
title: msg,
icon: 'none',
duration: 2000
})
}
}
export {
HTTP
}
// 示例
import {HTTP} from '../../utils/request.js';
let http = new HTTP();
// js
getList: function () {
http.request({
url: '/list',
success: (res) => {
// console.log(res.data)
})
},
网友评论