jhwxapp/miniprogram/utils/request.js

114 lines
2.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import config from '../config'
import {
getToken,
removeToken
} from './auth'
const app = getApp()
function doRequest(url, method = 'GET', data, header = {}) {
//安全白名单判断
if (config.noSecuritys.indexOf(url) == -1 && !getToken()) {
removeToken();
wx.redirectTo({
url: '../login/index',
});
}
wx.showLoading({
mask: true,
title: url == config.noSecuritys[1] ? '登录中' : '请等待'
})
return new Promise((resolve, reject) => {
wx.request({
url: config.baseUrl + url,
method: method,
data: data,
header: {
'content-type': 'application/json',
'Authorization': 'Bearer ' + getToken(),
...header
},
timeout: config.timeOut,
success: function (res) {
wx.hideLoading()
const code = res.data.code || 200
if (code === 401) {
removeToken();
wx.redirectTo({
url: '../pages/login/index',
});
} else if (code === 500 || code === 403) {
app.toast(res.data.msg,1500);
setTimeout(() => {
resolve(res.data);
}, 1200)
} else {
resolve(res.data);
}
},
fail: function (error) {
wx.hideLoading()
app.toast(error);
reject(error)
}
})
})
}
/**
* 这里考虑上传异步问题,封装为同步
*/
export function syncFileUpload(file) {
if (!getToken()) {
removeToken();
wx.redirectTo({
url: '../login/index',
});
}
wx.showLoading({
mask: true,
title: '正在上传资源'
})
return new Promise((resolve, reject) => {
wx.uploadFile({
url: config.baseUrl + '/wechat/common/upload', // 上传的服务器接口地址
filePath: file,
header: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
'Authorization': 'Bearer ' + getToken()
},
name: "file", //上传的所需字段,后端提供
formData: {},
success: (res) => {
// 上传完成操作
wx.hideLoading()
let resJson = JSON.parse(res.data)
const code = resJson.code || 200
if (code === 401) {
removeToken();
wx.redirectTo({
url: '../login/index',
});
} else if (code === 500 || code === 403) {
app.toast(resJson.msg);
setTimeout(() => {
resolve(resJson);
}, 800)
resolve(resJson);
} else {
resolve(resJson);
}
},
fail: (error) => {
wx.hideLoading()
//上传失败修改pedding为reject
app.toast("网络出错,上传失败")
reject(error)
}
});
})
}
export function request(options) {
return doRequest(options.url, options.method, options.data, options.header)
}