You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
zhishifufei_uniapp/utils/request.js

81 lines
2.1 KiB

9 months ago
import config from '@/config';
import { COOKIE_KEY } from '@/constants/storage-keys';
import store from "@/store";
import utils from '@/utils/utils';
const { HTTP_REQUEST_URL } = config;
function baseRequest(url, method, data, {
requireAuth = false,
moduleName = "wap",
plain = false
}) {
const header = {
'X-Requested-With': "XMLHttpRequest",
'X-Version': 'next'
};
// #ifdef MP
header['X-Platform'] = 'MiniProgram';
// #endif
if (requireAuth && !store.getters.isLogin) {
// #ifdef H5
if (utils.isWeixin())
return uni.redirectTo({
url: "/pages/login/wechat"
});
// #endif
const paths = getCurrentPages();
const path = paths[paths.length - 1].$page.fullPath;
uni.redirectTo({
url: "/pages/login/index?url=" + encodeURIComponent(path)
});
return Promise.reject({
msg: '未登录'
});
}
if (store.getters.isLogin && store.getters.token) {
header["Authorization"] = 'Bearer ' + store.getters.token;
}
return new Promise((reslove, reject) => {
uni.request({
url: HTTP_REQUEST_URL + "/" + moduleName + url,
method: method || 'GET',
header,
data: data || {},
success: (res) => {
if (plain) return reslove(res.data);
// #ifdef MP-WEIXIN
res.cookies.map(m => {
if (m.indexOf("PHPSESSID") != -1)
utils.setStorage(COOKIE_KEY, res.cookies.join(";"));
})
// #endif
if (res.data.code === 200) {
reslove(res.data);
} else {
reject(res.data);
}
},
fail: (err) => {
reject(err);
}
})
});
}
const request = {};
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});
export default request;