阅读 191

axios封装

import axios from 'axios';
import router from './../router'


axios.defaults.timeout = 5000;
axios.defaults.baseURL = 'http://test.*****.com/api';
axios.defaults.withCredentials = true;


//http request 拦截器
axios.interceptors.request.use(
config => {
config.data = JSON.stringify(config.data);
config.headers = {
'Content-Type': 'application/json; charset=UTF-8;'
}
return config;
},
error => {
return Promise.reject(err);
}
);


//http response 拦截器
axios.interceptors.response.use(
response => {
if (response.data.errorCode == 62000 || response.data.errorCode == 63002) {
router.push({
path: "/login",
querry: {
redirect: router.currentRoute.fullPath
} //从哪个页面跳转
})
}
return response;
},
error => {
return Promise.reject(error)
}
)


/**
* 封装get方法
* @param url
* @param data
* @returns {Promise}
*/

export function fetch(url, params = {}) {
return new Promise((resolve, reject) => {
axios.get(url, {
params: params
})
.then(response => {
resolve(response.data);
})
.catch(err => {
reject(err)
})
})
}


/**
* 封装post请求
* @param url
* @param data
* @returns {Promise}
*/

export function post(url, data = {}) {
return new Promise((resolve, reject) => {
axios.post(url, data)
.then(response => {
resolve(response.data);
}, err => {
reject(err)
})
})
}

/**
* 封装patch请求
* @param url
* @param data
* @returns {Promise}
*/

export function patch(url, data = {}) {
return new Promise((resolve, reject) => {
axios.patch(url, data)
.then(response => {
resolve(response.data);
}, err => {
reject(err)
})
})
}

/**
* 封装put请求
* @param url
* @param data
* @returns {Promise}
*/

export function put(url, data = {}) {
return new Promise((resolve, reject) => {
axios.put(url, data)
.then(response => {
resolve(response.data);
}, err => {
reject(err)
})
})
}

/**
* 封装delete请求
* @param url
* @param data
* @returns {Promise}
*/

export function remove(url, data = {}) {
return new Promise((resolve, reject) => {
axios.delete(url, data)
.then(response => {
resolve(response.data);
}, err => {
reject(err)
})
})
}


文章分类
前端