封装axios的getpost方法
Posted 六卿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了封装axios的getpost方法相关的知识,希望对你有一定的参考价值。
对axios的封装
import axios from 'axios'
import { ElMessage } from "element-plus";
import store from '../../store/index'
import router from '../../router'
let Ajax = axios.create({
baseURL: "http://127.0.0.1:8000/",
timeout: 50000
})
Ajax.interceptors.request.use(async config => {
config.cancelToken = new axios.CancelToken(cancel => {
store.commit('home/add_AxiosPromiseArr', { cancel })
})
// Do something before request is sent
return config;
}, error => {
return Promise.reject(error);
});
Ajax.interceptors.response.use(response => {
if (response?.data?.data?.code == 2) {
ElMessage(response.data.data.data)
router.push('/login')
localStorage.clear()
return []
}
if (response?.data?.data?.code == 0) {
ElMessage(response.data.data.data)
router.push('/login')
localStorage.clear()
return []
}
return response.data;
}, error => {
return Promise.reject(error);
});
const get = (url, params) => {
Ajax.defaults.headers['token'] = localStorage.getItem('token')
return new Promise((relove, reject) => {
Ajax.get(url, { params, headers: { responseType: 'arraybuffer' } }).then(res => relove(res)).catch(err => reject(err))
})
}
const getTIP = (url, params) => {
Ajax.defaults.headers['token'] = localStorage.getItem('token')
return new Promise((relove, reject) => {
Ajax.get(url, { params, responseType: "arraybuffer", headers: { responseType: 'arraybuffer' } }).then(res => relove(res)).catch(err => reject(err))
})
}
const post = (url, params) => {
Ajax.defaults.headers['token'] = localStorage.getItem('token')
return new Promise((relove, reject) => {
Ajax.post(url, params).then(res => relove(res)).catch(err => reject(err))
})
}
export default {
get, post, getTIP
}
以上是关于封装axios的getpost方法的主要内容,如果未能解决你的问题,请参考以下文章
VSCode自定义代码片段14——Vue的axios网络请求封装