xinsi_book/src/utils/request.js
caoyuchun 5542e7f6bb cyc
2024-06-18 15:53:13 +08:00

156 lines
3.8 KiB
JavaScript
Raw 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 axios from "axios";
// import config from '~/config';
import { getStore } from "./mUtils";
import Md5 from "crypto-js/md5";
// axios.defaults.timeout = 12000;
axios.defaults.headers = {
// 'Content-Type': 'application/json',
// 'Accept': 'application/json',
"Content-Type": "multipart/form-data",
};
// 请求拦截器
axios.interceptors.request.use(
(request) => {
// 如果请求是浏览器访问
// if (typeof window !== "undefined") {
// if ($nuxt.$store.getters.userInfo.token && $nuxt.$store.getters.userInfo.token !== "") {
// // 浏览器用户登录 token 不可删除 删除之后 用户ajax 用户登录失效
// request.headers["Authorization"] = "Token " + $nuxt.$store.getters.userInfo.token;
// } else {
// request.headers["Authorization"] = '';
// }
// } else {
// // 如果请求是服务端访问
// // console.log('当前是服务端环境')
// // axios.defaults.baseURL = config.BASE_URL;
// }
return request;
},
(error) => {
return Promise.reject(error);
}
);
export default async (options = { method: "GET" }) => {
let isdata = true;
if (
options.method.toUpperCase() !== "POST" &&
options.method.toUpperCase() !== "PUT" &&
options.method.toUpperCase() !== "PATCH" &&
options.method.toUpperCase() !== "DELETE"
) {
isdata = false;
}
// 发请求前 业务处理
var data = options.data;
// 设置公共报文逻辑
let time = Date.parse(new Date());
let keys = ["apikey", "sign", "time"];
for (const keysKey in data) {
keys.push(keysKey);
}
data.isTest = 1;
//
let key1 = keys.sort();
let key2 = key1.join("&");
let key3 = key2 + "&" + time + "&" + "HuaTeng987!@#";
// console.log(key3)
// console.log(data)
let sign = Md5(key3).toString();
//
let apikey = getStore("apikey");
if (apikey !== null) {
data.apikey = apikey;
} else {
data.apikey = "HT_6d671a62c1d668161552616453";
}
console.log('apikey=='+data.apikey)
// userId
let userId = getStore("userId");
if (userId !== null) {
data.userId = userId;
}
// 参数
data.sign = sign;
data.time = time;
var myheaders = {};
var mydata = data;
// 如果是 post 方法 需要设置 编码格式
if (options.method === "POST") {
myheaders = {
"Content-Type": "multipart/form-data",
};
let formData = new FormData();
for (const datakey in data) {
formData.append(datakey, data[datakey]);
}
mydata = formData;
}
//
try {
console.log(options.url)
const res = await axios({
method: options.method,
url: options.url,
data: mydata,
params: mydata,
headers: myheaders,
});
// code == 200 报错
if(res.data.code !== 200){
return new Promise((resolve,reject)=>reject(res.data.msg));
}
return new Promise((resolve,reject)=>resolve(res.data.data))
} catch (error) {
if (axios.isAxiosError(error)) {
if (error.response) {
// 请求已发出,服务器响应了状态码,但状态码不在 2xx 范围内
// if (error.response.status === 403) {
// console.error('Access forbidden: You do not have permission to access this resource.');
// } else {
// console.error(`Error: Received status code ${error.response.status}`);
// }
console.log(error.response)
} else if (error.request) {
// 请求已发出但没有收到响应
console.error('No response received:', error.request);
} else {
// 设置请求时发生了错误
console.error('Error setting up request:', error.message);
}
} else {
// 处理非 Axios 错误
console.error('An unexpected error occurred:', error.message);
}
}
};