beelink/src/config/axiosConfig.ts
2020-12-07 12:09:56 +08:00

86 lines
2.1 KiB
TypeScript
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 { getValue } from '@/utils/common';
import Axios from 'axios'
Axios.defaults.baseURL = 'https://case.sy-my.net/beelink/public/home/';
if(getValue("time") < (new Date().getTime() - 12 * 60 * 60 * 1000)){
localStorage.removeItem("token")
localStorage.removeItem("time")
}
Axios.defaults.headers.common['Authorization'] = "Bearer " + getValue("token");
Axios.defaults.headers.common['Language'] = !getValue("Lanvuage") ? 'zh' : getValue("Lanvuage");
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
interface Data {
[url: string]: {
data: any;
time: number;
};
}
class Huancun {
data: Data = {}
has(url: string){
// console.log(this.data)
// if(!this.data[url]){
// return false;
// }
// console.log(new Date().getTime() - 60000 < this.data[url].time,"time")
// if(this.data[url] && new Date().getTime() - 60000 < this.data[url].time){
// return this.data[url]
// }else {
// return false
// }
return false;
}
save(url: string,data: any){
this.data[url] = {data,time: new Date().getTime()}
}
}
const huancun = new Huancun()
Axios.interceptors.response.use((res)=>{
console.log(res,"data")
if(res.config.url){
huancun.save(res.config.url,res);
}
return res;
})
const axios = Axios.create({
adapter: config =>{
// 判断是否存在mock数据
let has: any;
if(config.url){
has = huancun.has(config.url)
}
console.log(has,"has")
// 调用默认请求接口, 发送正常请求及返回
if(!has){
// 删除配置中的 adapter, 使用默认值
delete config.adapter
// 通过配置发起请求
return Axios(config)
}
// 模拟服务返回mock数据
return new Promise((res) =>{
console.log(has.data)
// 调用响应函数
res(has.data)
})
}
})
export default axios