how do you configure a request timestamp in axios.js
I found that the API written by the backend has a caching mechanism.
so write one.
is it convenient to write a
here is the axios encapsulation code I wrote
// vuexloading
// import store from "@/store"
export default function $axios(options) {
return new Promise((resolve, reject) => {
const instance = axios.create({
baseURL: config.baseUrl,
headers: config.headers
})
// request
instance.interceptors.request.use(
config => {
let token = Cookies.get("token")
// 1. vuex loading
// console.log(store.state.loading)
// console.log("...")
// 2. token
if (token) {
config.headers.token = token
} else {
//
router.push("/login")
}
// 3.
if (config.method === "post") {
// if (config.data.__proto__ === FormData.prototype
// || config.url.endsWith("path")
// || config.url.endsWith("mark")
// || config.url.endsWith("patchs")
// ) {
// } else {
// config.data = qs.stringify(config.data)
// }
}
return config
},
error => {
//
console.log("request:", error)
// 1.
if (error.code === "ECONNABORTED" && error.message.indexOf("timeout") !== -1) {
console.log("timeout")
// return service.request(originalRequest);//
}
// 2.
const errorInfo = error.response
console.log(errorInfo)
if (errorInfo) {
error = errorInfo.data // catch,Promise.reject
const errorStatus = errorInfo.status; // 404 403 500 ...
router.push({
path: `/error/${errorStatus}`
})
}
return Promise.reject(error) // (catch)
}
)
// response
instance.interceptors.response.use(
response => {
let data;
// IE9response.dataundefinedresponse.request.responseText(Stringify)
if (response.data == undefined) {
data = JSON.parse(response.request.responseText)
} else {
data = response.data
}
// code
switch (data.rc) {
case 1:
console.log(data.desc)
break;
case 0:
store.commit("changeState")
// console.log("")
default:
}
// code
// const err = new Error(data.desc)
// err.data = data
// err.response = response
// throw err
return data
},
err => {
if (err && err.response) {
switch (err.response.status) {
case 400:
err.message = ""
break
case 401:
err.message = ""
break
case 403:
err.message = ""
break
case 404:
err.message = `: ${err.response.config.url}`
break
case 408:
err.message = ""
break
case 500:
err.message = ""
break
case 501:
err.message = ""
break
case 502:
err.message = ""
break
case 503:
err.message = ""
break
case 504:
err.message = ""
break
case 505:
err.message = "HTTP"
break
default:
}
}
console.error(err)
return Promise.reject(err) //
}
)
//
instance(options).then(res => {
resolve(res)
return false
}).catch(error => {
reject(error)
})
})
}