这是一个简单的封装,做下记录。代码有做解释
新建请求类
http.js
var Http = {
baseUrl: '',//请求的基础地址:www.baidu.com/
headers: {//具体配置看个人需求
// authorization: '',
// pid: '',
// appid: '',
// 'X-ClientId': '',
// From: 'Platform',
},
/**
* [HTTP 请求]
*
*/
request: function (option) {
const { url, method, data, params } = option;
let newPath = url;
//如果是post请求且params存在 则将params拼接于请求地址后面
if (method.toLocaleUpperCase() == 'POST' && params) {
let str = '';
Object.keys(params).forEach((key, index) => {
if (index === 0) {
str += `?${key}=${params[key]}`;
} else {
str += `&${key}=${params[key]}`;
}
});
newPath += str;
}
//具体实现
return Http.Request(method.toLocaleUpperCase(), {
url: newPath,
params: data || params || {},
});
},
// request
Request: function (method, requestHandler) {
//loading:true;false
//mask:是否显示透明蒙层,防止触摸穿透
const { url, params, headers, mask, loading } = requestHandler;
let url_ = '';
if (!url.startsWith('http')) {
url_ = `${this.baseUrl}${url}`;
} else {
url_ = url;
}
//是否请求加Loading....
if (loading) {
// wx.showLoading && wx.showLoading({
// title: 'Loading...',
// mask: mask ? mask : false
// })
}
return new Promise((resolve, reject) => {
wx.request({
url: url_,
data: params,
method: ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'].indexOf(method) > -1 ? method : 'GET',
header: Object.assign(this.headers, headers),
success: function (res) {
const { data, statusCode } = res;
// 处理数据:根据接口的放回状态码去确定:例如下面
if (statusCode === 200 || statusCode === 204) {//成功
resolve(data);
} else {//失败处理:最后把加reject;不然在接口调用的地方,无法拦截做一些其他事情
if (statusCode === 400) {
wx.showToast({
title: '参数有误',
icon: 'error',
});
} else if (statusCode === 401) {
console.log('没登陆;或者登陆过期');
} else if (statusCode === 403) {
wx.showModal({
title: '温馨提示',
content: data.error.message,
showCancel: false,
});
} else if (statusCode === 500) {
wx.showToast({
title: '系统错误',
icon: 'error',
});
}
reject(data, statusCode);
}
},
fail: function () {
reject('Network request failed');
},
complete: function () {
console.log('接口调用完成,关闭弹窗:wx.hideLoading');
},
});
});
},
};
//导出
module.exports = Http;
使用:伪代码
const http = require('../../utils/http');
const request = http.request;
class testApi {
//post
static post_method(data) {
return request({
url: `/platform/api/Account/resetPassword`,
method: 'post',
data: data,
});
}
static post_method1(params,data) {
return request({
url: `/platform/api/Account/resetPassword`,
method: 'post',
data: data,
params:params,
});
}
static post_method2(params) {
return request({
url: `/platform/api/Account/resetPassword`,
method: 'post',
params:params,
});
}
static get_method(params) {
return request({
url: `/platform/api/Account/resetPassword`,
method: 'get',
params:params
});
}
//detele
static del(params){
return request({
url: `/mg/api/Announce/del`,
method: 'delete',
params: params,
});
}
}