zlpt_app/http/request.js

825 lines
21 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import base from "@/common/config/domain.js"
import {md5} from "@/common/js/md5.js"
const baseUrl = base.baseUrl
const wsUrl = base.wsUrl
let ajaxTimes = 0;
//需要跳转到登录页的接口
let login_list=[
'/game/app/question/queryTrainQuest',
'/game/operate/joinGame',
'/user/app/feat/getAllFeatInfo'
];
/*
url接口地址
data数据
needtoken是否需要令牌
domain请求域名
*/
export const get = (url, data = {}, needtoken = true, domain) => {
let header = defaultHeader();
// let header = {
// // "content-type": "application/json",
// Authorization: handleToken(),
// };
let token = handleToken();
let http_base = {
url: domain ? domain + url : baseUrl + url,
data: data,
method: "GET",
header:{
...header
}
}
// console.log("domain",domain)
if (needtoken) {
//拦截需要登录的名单跳转到登录页面
// console.log("login_list.indexOf(url)",login_list.indexOf(url));
if(login_list.indexOf(url)>=0 && !token){
//需要登录
uni.navigateTo({
url:'/pages/login/index'
})
return ;
// return new Promise((resolve, reject) => {
// reject('需要先登录');
// });
}
http_base.header.Authorization =token;
} else {
if (token) {
http_base.header.Authorization =token;
}
}
return new Promise((resolve, reject) => {
uni.request({
...http_base,
success: (res) => {
// console.log("getres",res);
if (res.statusCode == 200) {
if (typeof res.data == "string") {
res.data = JSON.parse(res.data);
}
if (res.data.code == "1000") {
resolve(res.data);
} else {
authCase(res.data, url)
reject(res);
}
} else {
reject(res);
}
},
fail: (err) => {
console.log("请求失败",err);
uni.showToast({
title:"网络异常,请检查网络",
icon:"none",
duration:2000,
})
reject(err);
},
complete: (com) => {
},
});
});
};
/*
url接口地址
data数据
needtoken是否需要令牌
domain请求域名
*/
export const post = (url, data = {}, needtoken = true, domain) => {
let header = defaultHeader();
let token = handleToken();
let http_base = {
url: domain ? domain + url : baseUrl + url,
data: data,
method: "POST",
header:{
...header,
"content-type": "application/json",
}
}
if (needtoken) {
console.log("login_list.indexOf(url)",url,login_list.indexOf(url));
//拦截需要登录的名单跳转到登录页面
if(login_list.indexOf(url)>=0 && !token){
console.log(1)
//需要登录
uni.navigateTo({
url:'/pages/login/index'
})
return ;
// return new Promise((resolve, reject) => {
// reject('需要先登录');
// });
}
http_base.header.Authorization =token;
} else {
if (token) {
http_base.header.Authorization =token;
}
}
return new Promise((resolve, reject) => {
uni.request({
...http_base,
success: (res) => {
if (res.statusCode == 200) {
if (typeof res.data == "string") {
res.data = JSON.parse(res.data);
}
if (res.data.code == "1000") {
resolve(res.data);
} else {
authCase(res.data, url)
reject(res);
}
} else {
reject(res);
}
},
fail: (err) => {
console.log("请求失败",err);
uni.showToast({
title:"网络异常,请检查网络",
icon:"none",
duration:2000,
})
reject(err);
},
complete: (com) => {
},
});
});
};
function handleToken() {
let tokenC = uni.getStorageSync('token');
// tokenC = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NTEwMzY5MjcsInVzZXJJZCI6Ijk5MjYzODg2Nzg4MDI4NDE2MF8xNjUwOTUwNTI3NTc3In0.ID2vAMfd2AYb6h5Ir9l-dcH9RBF0hrtkn4en8w8kL2U'
// let tokenC = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NTQ4NzMzOTUsInVzZXJJZCI6ImFwcF8xMCJ9.S6sI9wmo3JlU5W-HD1b4fULUqKN7LpYhFVj0O9EZjuU"
return tokenC
}
/*
@param上传文件
file uniapp的choosefile获取到的文件临时信息
url 上传的url地址
name 上传给服务器端的字段名称默认file
type_set上传的文件类型 默认['.pdf','.doc','.ppt','.pptx','.png','.jpg','.jpeg']
filekey 储存的路径,更新原有文件
success 成功
fail 失败
max_size 文件最大的大小单位mb
onProgress获取上传进度信息
*/
export const uploadFile = (param, needtoken = true) => {
console.log("param.file",param.file);
let header = defaultHeader();
let file_name = param.file.tempFiles[0].name;
let file_size = param.file.tempFiles[0].size / 1024 / 1024;
let type_list = file_name.split('.');
let file_type = null;
if (type_list.length > 0) {
file_type = type_list[type_list.length - 1];
// console.log("file_type",file_type);
//截取文件名140字内
let name_list = JSON.parse(JSON.stringify(type_list));
name_list.pop();
let full_name=name_list.join('.');
full_name=full_name.slice(0,140);
file_name=`${full_name}.${file_type}`;
}
//查找是否在范围内的
let can_upload = false;
let type_set = param.type_set ? param.type_set : ['pdf', 'doc', 'ppt', 'pptx', 'png', 'jpg', 'jpeg'];
// console.log(file_size,file_type);
// console.log('type_set',type_set);
if (file_type) {
console.log("type_set.indexOf('.' + file_type)",type_set.indexOf(file_type));
if (type_set.indexOf(file_type) >= 0) {
can_upload = true;
}
}
let max_size=param && param.max_size?param.max_size:10;
// console.log("max_size",max_size);
if (can_upload && file_size <= max_size) {
//可以上传的类型
let nowTime = new Date();
let year = nowTime.getFullYear();
let month = nowTime.getMonth() + 1;
let day = nowTime.getDate();
let time = nowTime.getTime();
let filekey = param.filekey ? param.filekey :
`/${year}/${month}/${day}/${time}_${Math.floor(Math.random()*100)}.${file_type}`;
console.log("filekey",filekey);
// console.log(year,month,day,time,filekey)
// console.log('url',baseUrl+param.url);
let http_base = {
url: baseUrl + param.url, //仅为示例,非真实的接口地址
filePath: param.file.tempFiles[0].path,
name: param.name ? param.name : 'file',
formData: {
'fileKey': filekey,
},
header:{
...header
}
}
if (needtoken) {
http_base.header.Authorization =handleToken();
}
const uploadTask = uni.uploadFile({
// url:baseUrl+param.url, //仅为示例,非真实的接口地址
// filePath: param.file.tempFilePaths[0],
// name: param.name?param.name:'file',
// header:{Authorization: handleToken()},
// formData: {
// 'fileKey': filekey
// },
...http_base,
success: (res) => {
console.log('提交返回', res);
if (typeof res.data == "string") {
res.data = JSON.parse(res.data)
}
if (res.data.code == 1000) {
res.data.data.fileName = file_name;
res.data.data.file_type = file_type;
res.data.data.resumeName = res.data.data.fileName;
res.data.data.resumeFileKey = filekey;
var update = new Date();
res.data.data.updateTime = update.toLocaleString('zh',{hour12:false});
// console.log('res',res);
param.success && param.success(res)
} else {
param.fail && param.fail(res)
}
},
fail: (res) => {
param.fail && param.fail(res)
}
});
if (param.onProgress) {
uploadTask.onProgressUpdate((res) => {
// console.log('上传进度' + res.progress);
// console.log('已经上传的数据长度' + res.totalBytesSent);
// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
param.onProgress(res);
// 测试条件,取消上传任务。
// if (res.progress > 50) {
// uploadTask.abort();
// }
});
}
} else {
//不可以上传
let msg
if (!can_upload) {
let type_str=type_set.join("、");
msg = `仅支持${type_str}类型文件`;
}
if (file_size > max_size) {
msg = `大小不能超过${max_size}MB`;
}
param.fail && param.fail({
msg: msg
})
uni.showToast({
title: msg,
icon: 'none'
})
}
}
/*
setCvDetail上传附件简历
@param上传文件
file uniapp的choosefile获取到的文件临时信息
url 上传的url地址
name 上传给服务器端的字段名称默认file
type_set上传的文件类型 默认['.pdf','.doc','.ppt','.pptx','.png','.jpg','.jpeg']
filekey 储存的路径,更新原有文件
success 成功
fail 失败
max_size 文件最大的大小单位mb
onProgress获取上传进度信息
cvId 简历id
*/
export const setCvDetail = (param, needtoken = true) => {
console.log("param.file",param.file);
let header = defaultHeader();
let file_name = param.file.tempFiles[0].name;
let file_size = param.file.tempFiles[0].size / 1024 / 1024;
let type_list = file_name.split('.');
let file_type = null;
if (type_list.length > 0) {
file_type = type_list[type_list.length - 1];
// console.log("file_type",file_type);
//截取文件名140字内
let name_list = JSON.parse(JSON.stringify(type_list));
name_list.pop();
let full_name=name_list.join('.');
full_name=full_name.slice(0,140);
file_name=`${full_name}.${file_type}`;
}
//查找是否在范围内的
let can_upload = false;
let type_set = param.type_set ? param.type_set : ['pdf', 'doc', 'ppt', 'pptx', 'png', 'jpg', 'jpeg'];
// console.log(file_size,file_type);
// console.log('type_set',type_set);
if (file_type) {
console.log("type_set.indexOf('.' + file_type)",type_set.indexOf(file_type));
if (type_set.indexOf(file_type) >= 0) {
can_upload = true;
}
}
let max_size=param && param.max_size?param.max_size:10;
// console.log("max_size",max_size);
if (can_upload && file_size <= max_size) {
//可以上传的类型
let nowTime = new Date();
let year = nowTime.getFullYear();
let month = nowTime.getMonth() + 1;
let day = nowTime.getDate();
let time = nowTime.getTime();
let filekey = param.filekey ? param.filekey :
`/${year}/${month}/${day}/${time}_${Math.floor(Math.random()*100)}.${file_type}`;
console.log("filekey",filekey);
// console.log(year,month,day,time,filekey)
// console.log('url',baseUrl+param.url);
let formData={
'cvName':file_name,
'cvPath': filekey,
}
if(param.cvId){
formData.cvId=param.cvId;
}
let http_base = {
url: baseUrl + param.url, //仅为示例,非真实的接口地址
filePath: param.file.tempFiles[0].path,
name: param.name ? param.name : 'cvFile',
formData: formData,
header:{
...header
}
}
if (needtoken) {
http_base.header.Authorization =handleToken();
}
console.log("formData",formData);
const uploadTask = uni.uploadFile({
// url:baseUrl+param.url, //仅为示例,非真实的接口地址
// filePath: param.file.tempFilePaths[0],
// name: param.name?param.name:'file',
// header:{Authorization: handleToken()},
// formData: {
// 'fileKey': filekey
// },
...http_base,
success: (res) => {
console.log('提交返回', res);
if (typeof res.data == "string") {
res.data = JSON.parse(res.data)
}
if (res.data.code == 1000) {
let file_info={};
file_info.fileName = file_name;
file_info.file_type = file_type;
file_info.resumeName = file_name;
file_info.resumeFileKey = filekey;
file_info.cvId = res.data.data;
var update = new Date();
file_info.updateTime = update.toLocaleString('zh',{hour12:false});
// console.log('res',res);
res.data.data=file_info;
param.success && param.success(res)
} else {
param.fail && param.fail(res)
}
},
fail: (res) => {
uni.showToast({
title:"网络异常,请检查网络",
icon:"none",
duration:2000,
})
param.fail && param.fail(res)
}
});
if (param.onProgress) {
uploadTask.onProgressUpdate((res) => {
// console.log('上传进度' + res.progress);
// console.log('已经上传的数据长度' + res.totalBytesSent);
// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
param.onProgress(res);
// 测试条件,取消上传任务。
// if (res.progress > 50) {
// uploadTask.abort();
// }
});
}
} else {
//不可以上传
let msg
if (!can_upload) {
let type_str=type_set.join("、");
msg = `仅支持${type_str}类型文件`;
}
if (file_size > max_size) {
msg = `大小不能超过${max_size}MB`;
}
param.fail && param.fail({
msg: msg
})
uni.showToast({
title: msg,
icon: 'none'
})
}
}
export const uploadFileMore = (param, needtoken = true) => {
let header = defaultHeader();
if (param.index >= param.file.tempFiles.length) {
return
}
let file_name = param.file.tempFiles[param.index].path;
console.log("file_name", file_name);
let file_size = param.file.tempFiles[param.index].size / 1024 / 1024;
let type_list = file_name.split('.');
//兼容h5
if (type_list.length == 1) {
type_list.push('png');
}
console.log("type_list", type_list);
let file_type = null;
if (type_list.length > 0) {
file_type = type_list[type_list.length - 1];
}
console.log("file_type", file_type);
//查找是否在范围内的
let can_upload = false;
let type_set = param.type_set ? param.type_set : ['.pdf', '.doc', '.ppt', '.pptx', '.PNG', '.JPG', '.JPEG'];
// console.log(file_size,file_type);
// console.log('type_set',type_set);
console.log("type_set", type_set, file_type)
if (file_type) {
if (type_set.indexOf('.' + file_type) >= 0) {
can_upload = true;
}
}
console.log("can_upload", can_upload);
if (can_upload && file_size < 10) {
//可以上传的类型
let nowTime = new Date();
let year = nowTime.getFullYear();
let month = nowTime.getMonth() + 1;
let day = nowTime.getDate();
let time = nowTime.getTime();
let filekey
if (param.fileType) {//新增的fileType 参数 兼容到没有传 fileType的 各位大佬看见了自己改下自己的代码
filekey = param.filekey ? param.filekey :
`/${param.fileType}/${year}/${month}/${day}/${time}_${Math.floor(Math.random()*100)}.${file_type}`;
} else {
filekey = param.filekey ? param.filekey :
`/${year}/${month}/${day}/${time}_${Math.floor(Math.random()*100)}.${file_type}`;
}
// console.log(year,month,day,time,filekey)
// console.log('url',baseUrl+param.url);
let http_base = {
url: baseUrl + param.url, //仅为示例,非真实的接口地址
filePath: param.file.tempFilePaths[param.index],
name: param.name ? param.name : 'file',
formData: {
'fileKey': filekey,
},
header:{
...header
}
}
if (needtoken) {
http_base.header.Authorization =handleToken();
}
console.log("http_base", http_base)
const uploadTask = uni.uploadFile({
// url:baseUrl+param.url, //仅为示例,非真实的接口地址
// filePath: param.file.tempFilePaths[0],
// name: param.name?param.name:'file',
// header:{Authorization: handleToken()},
// formData: {
// 'fileKey': filekey
// },
...http_base,
success: (res) => {
console.log('提交返回', res);
if (typeof res.data == "string") {
res.data = JSON.parse(res.data)
}
if (res.data.code == 1000) {
res.data.data.file_type = file_type;
res.data.data.resumeName = res.data.data.fileName;
res.data.data.resumeFileKey = filekey;
var update = new Date();
res.data.data.updateTime = update.toLocaleString();
// console.log('res',res);
param.success && param.success(res)
param.index++
uploadFileMore(param, true)
} else {
param.fail && param.fail(res)
}
},
fail: (res) => {
param.fail && param.fail(res)
}
});
if (param.onProgress) {
uploadTask.onProgressUpdate((res) => {
// console.log('上传进度' + res.progress);
// console.log('已经上传的数据长度' + res.totalBytesSent);
// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
param.onProgress(res);
// 测试条件,取消上传任务。
// if (res.progress > 50) {
// uploadTask.abort();
// }
});
}
} else {
//不可以上传
let msg
if (!can_upload) {
msg = "不支持该类型"
}
if (file_size >= 10) {
msg = "只支持10MB内的文件"
}
param.fail && param.fail({
msg: msg
})
uni.showToast({
title: msg,
icon: 'none'
})
}
}
export const uploadVideo = (param, needtoken = true) => {
let header = defaultHeader();
let file_name = param.file.tempFilePath
console.log("file_name", file_name);
let file_size = param.file.size / 1024 / 1024;
let type_list = file_name.split('.');
console.log("type_list", type_list);
let file_type = null;
if (type_list.length > 0) {
file_type = type_list[type_list.length - 1];
}
console.log("file_type", file_type);
//查找是否在范围内的
let can_upload = false;
let type_set = param.type_set ? param.type_set : ['.mp4'];
// console.log(file_size,file_type);
// console.log('type_set',type_set);
console.log("type_set", type_set, file_type)
if (file_type) {
if (type_set.indexOf('.' + file_type) >= 0) {
can_upload = true;
}
}
console.log("can_upload", can_upload);
if (can_upload && file_size < 10) {
//可以上传的类型
let nowTime = new Date();
let year = nowTime.getFullYear();
let month = nowTime.getMonth() + 1;
let day = nowTime.getDate();
let time = nowTime.getTime();
let filekey
if (param.fileType) {//新增的fileType 参数 兼容到没有传 fileType的 各位大佬看见了自己改下自己的代码
filekey = param.filekey ? param.filekey :
`/${param.fileType}/${year}/${month}/${day}/${time}_${Math.floor(Math.random()*100)}.${file_type}`;
} else {
filekey = param.filekey ? param.filekey :
`/${year}/${month}/${day}/${time}_${Math.floor(Math.random()*100)}.${file_type}`;
}
// console.log(year,month,day,time,filekey)
// console.log('url',baseUrl+param.url);
let http_base = {
url: baseUrl + param.url, //仅为示例,非真实的接口地址
filePath: param.file.tempFilePath,
name: param.name ? param.name : 'file',
formData: {
'fileKey': filekey,
},
header:{
...header
}
}
if (needtoken) {
http_base.header.Authorization =handleToken();
}
console.log("http_base", http_base)
const uploadTask = uni.uploadFile({
// url:baseUrl+param.url, //仅为示例,非真实的接口地址
// filePath: param.file.tempFilePaths[0],
// name: param.name?param.name:'file',
// header:{Authorization: handleToken()},
// formData: {
// 'fileKey': filekey
// },
...http_base,
success: (res) => {
console.log('提交返回', res);
if (typeof res.data == "string") {
res.data = JSON.parse(res.data)
}
if (res.data.code == 1000) {
res.data.data.file_type = file_type;
res.data.data.resumeName = res.data.data.fileName;
res.data.data.resumeFileKey = filekey;
var update = new Date();
res.data.data.updateTime = update.toLocaleString();
// console.log('res',res);
param.success && param.success(res)
} else {
param.fail && param.fail(res)
}
},
fail: (res) => {
param.fail && param.fail(res)
}
});
if (param.onProgress) {
uploadTask.onProgressUpdate((res) => {
// console.log('上传进度' + res.progress);
// console.log('已经上传的数据长度' + res.totalBytesSent);
// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
param.onProgress(res);
// 测试条件,取消上传任务。
// if (res.progress > 50) {
// uploadTask.abort();
// }
});
}
} else {
//不可以上传
let msg
if (!can_upload) {
msg = "不支持该类型"
}
if (file_size >= 10) {
msg = "只支持10MB内的文件"
}
param.fail && param.fail({
msg: msg
})
uni.showToast({
title: msg,
icon: 'none'
})
}
}
export const upload = (url, data = {}, needtoken = false) => {
let header = defaultHeader();
let http_base = {
url: baseUrl + url,
name: data.name || 'file',
filePath: data.file.path,
formData: {
fileKey: data.fileKey
},
header:{
...header
}
}
if (needtoken) {
http_base.header.Authorization =handleToken();
}
return new Promise((resolve, reject) => {
uni.uploadFile({
...http_base,
success: (res) => {
if (res.statusCode == 200) {
if (typeof res.data == "string") {
res.data = JSON.parse(res.data);
}
if (res.data.code == "1000") {
resolve(res.data);
} else {
authCase(res.data, url)
reject(res);
}
} else {
reject(res);
}
},
fail: (res) => {
reject(res.data);
},
complete: (com) => {
},
});
});
};
//设置请求头
function defaultHeader(){
return header;
}
// 通过errorcode的拦截提示
function authCase(res, url) {
const {code, msg, data} = res
switch (code) {
case 6001: // 您已将该用户拉黑无法对TA进行该操作
case 6002: // 由于对方的隐私设置您无法对TA进行该操作
uni.showToast({
icon: 'none',
title: msg,
duration: 1500
});
break;
default:
break;
}
// switch (code) {
// case 1004: //签名有误
// break;
// case 4000: //请求参数有误
// break;
// case 4001: //请求参数有误
// break;
// default:
// break;
// }
}