微信小程序 请求封装
项目根目录下新建http
文件夹
- 新建
http\api.js
import { wxRequest, get, post, getWxLoginCode } from './request.js'
const apiURL = "http://www.xxx.com/api";
export const getUserInfo = p => get(`${apiURL}/v1/user`, p);
- 新建
http\request.js
const wxRequest = (url, params, method) => {
wx.showLoading({
title: "加载中",
});
return new Promise((resolve, reject) => {
wx.request({
url,
method: method || "GET",
data: params || {},
header: {
Accept: "application/json",
"Content-Type": "application/json",
},
success(res) {
wx.hideLoading();
if (res.data.code == 200) {
// 成功
resolve(res.data);
} else {
// 失败
wx.hideLoading({
success: function () {
wx.showToast({
title: res.data.message,
icon: "none",
duration: 2000,
});
},
});
}
},
fail(res) {
reject(res);
wx.hideLoading({
success: function () {
wx.showToast({
title: "请检查网络设置!",
icon: "none",
duration: 2000,
});
},
});
},
});
});
};
const get = (url, params) => {
return wxRequest(url, params, 'GET');
}
const post = (url, params) => {
return wxRequest(url, params, 'POST');
}
// 微信登录,获取code
const getWxLoginCode = () => {
return new Promise((resolve, reject) => {
wx.login({
success: res => {
//获取code
resolve(res.code)
}
})
})
}
export {
wxRequest,
get,
post,
getWxLoginCode
};