版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
小程序请求,wx.request 请求封装
// 提示与加载工具类
export default class Tips {
static success(title) {
wx.showToast({
title: title,
icon: 'success',
duration: 2000
})
}
static error(title) {
wx.showToast({
title: title ||'出错啦~',
image: '/static/images/error.png',
mask: true,
duration: 1500
})
}
// 请求封装
/**
*@params url string 接口地址
*@params data object 请求参数
*@prams [method] string 请求方式GET||POST
*@prams [header] string 请求头类型
**/
const host = 'localhost:8080'//仅为示例,并非真实的地址
export function request(url, data, method, header) {
wx.showLoading({
title: '加载中' // 数据请求前loading
})
return new Promise((resolve, reject) => {
wx.request({
url: host + url, // 仅为示例,并非真实的接口地址
method: method || 'POST',
data: data,
header: {
'Authorization': '',
'content-type': header || 'application/json', // 默认值
'sign': '',
}, //配置请求头
success: function (res) {
//请求成功回调
wx.hideLoading();
if (!res.data.success) {
//请求有响应,但有异常
Tips.error(res.data.msg)
}
resolve(res.data)
},
fail: function (error) {
//请求失败
wx.hideLoading();
Tips.error(error.msg)
reject(error.msg)
},
complete: function () {
wx.hideLoading();
}
})
})
}
export function get(url, data) {
return request(url, data, 'GET')
}
export function post(url, data) {
return request(url, data, 'POST')
}
使用方式
import {
request
} from '@/utils/index.js'
export const getActDetail = (params) => request('app/user?id='+params, {}, 'GET', '')
export const getActList = (params) => request('app/page', params, 'POST', '')