api.js
const app = getApp();
let postApi = function (apiUrl, data, successCallback, errorCallback, completeCallback){
let apiData = {};
if (data){
apiData=data;
}
apiData.user_token=app.globalData.userToken;
wx.request({
url: app.rootUrl + apiUrl,
method: "POST",
data: apiData,
success: res => {
successCallback(res.data);
},
fail: err => {
if (errorCallback){
errorCallback(err);
}else{
wx.showToast({
title: e,
icon: 'none',
duration: 1500,
mask: false
})
}
},
complete: () => {
if (completeCallback) {
completeCallback();
}
}
})
}
export default postApi;
注意:在app.js中定义rootUrl,rootUrl是接口url的公共部分 ,apiUrl是接口url的剩余部分
index.js中调用接口
const app = getApp();
import postApi from "../../api.js";
postApi("apiUrl?_tq=" + new Date().getTime(), data, res => {
if (res.code == 0) {
//请求成功执行
}
})
// export const API_URL = ''; // 项目域名
/**
* 网络请求封装 fetch
*/
export default function fetch(url, params, showLoading = true, method) {
if (showLoading) {
wx.showLoading({ title: '加载中' });
}
var cookie = wx.getStorageSync('cookie');
if (!cookie) {
cookie = '';
}
return new Promise((resolve, reject) => {
wx.request({
url: `${API_URL}${url}`,
data: params || {},
method: method || 'post',
header: {
"Accept": "*/*",
"Content-Type": "application/json; charset=UTF-8'",
"Cookie": cookie,
},
success: res => {
resolve(res.data);
},
fail: error => {
reject(error);
},
complete() {
if (showLoading) {
wx.hideLoading();
}
}
})
})
}
在app.js文件引入该文件
在页面调用接口
在页面引入const app = getApp();
getWxUser(userD) {
var params = {
name:user.name,
phone:userD.phone
}
app.fetch(接口地址, params).then(
ret => {
if (ret.status) {
} else {
wx.showModal({
showCancel: false,
content: ret.errmsg
});
}
}
)
},
2023.07.28 更新
import siteinfo from '../../siteinfo';
export const apis = (url, params, method = 'POST') => {
let config = {};
var cookie = wx.getStorageSync('cookie');
if (!cookie) {
cookie = '';
}
config['method'] = method;
config['url'] = siteinfo.apiUrl + url;
if (method == 'POST') {
config['data'] = params;
} else if (method == 'GET') {
config['params'] = params;
}
return new Promise((resolve, reject) => {
wx.request({
...config,
header: {
'Content-Type': 'application/json; charset=UTF-8',
"Cookie": cookie
},
success(request) {
resolve(request.data);
wx.hideLoading();
},
fail() {
wx.hideLoading();
reject();
}
})
})
}
siteinfo.js文件与app.json文件同级,里面是小程序的基本配置,详细见这篇文章