https://juejin.im/post/5b55c118f265da0f6f1aa354
import axiosfrom 'axios'
import QSfrom 'qs'
// import router from '../routes'
axios.defaults.timeout =5000;//请求超时5秒
axios.defaults.baseURL ='';//请求base url
axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';//设置post请求是的header信息
axios.defaults.withCredentials =true;// 如果你要用到session验证码功能,让请求携带cookie
axios.defaults.headers['X-Requested-With'] ='XMLHttpRequest';
let instance = axios.create({
headers: {'content-type':'multipart/form-data'}
});
//http request 拦截器
axios.interceptors.request.use(
config => {
const AUTH_TOKEN = sessionStorage.getItem('token');
if (AUTH_TOKEN) {// 判断是否存在token,如果存在的话,则每个http header都加上token
config.headers['Authorization']= AUTH_TOKEN
}
return config
},
err => {
return Promise.reject(err)
}
);
axios.interceptors.response.use(
response => {
return response
},
err => {
return Promise.reject(err)
}
);
/**
* get方法,对应get请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
export const get = (url, params) => {
return new Promise((resolve, reject) => {
axios
.get(url, {
params: params
})
.then(res => {
resolve(res.data)
})
.catch(err => {
reject(err.data)
})
})
};
/**
* post方法,对应post请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
export const post = (url, ...params) => {
return new Promise((resolve, reject) => {
axios
.post(url, QS.stringify(...params))
.then(res => {
resolve(res.data)
})
.catch(err => {
reject(err.data)
})
})
};
/**
* delet方法,对应delett请求
* @param {String} url [请求的url地址]
* delete关键字会和vue系统关键字冲突,所以这里用delet代替
* delete用于删除,参数一般带在url
*/
export const delet = (url, params) => {
return new Promise((resolve, reject) => {
axios
.delete(url, {
params: params
})
.then(res => {
resolve(res.data)
})
.catch(err => {
reject(err.data)
})
})
};
/**
* patch方法,对应patch请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
* 这里根据需求适应了formdata的格式,也可以跟post用一样的封装
*/
export const patch = (url, params) => {
// 将数据转换为formData格式
// 正常情况下可以直接使用参数对象进行patch,如果出错可以尝试转换form Data
var formData =new FormData();
formData.append('account', params.account);
formData.append('password', params.password);
return new Promise((resolve, reject) => {
axios
.patch(url, formData)
.then(res => {
resolve(res.data)
})
.catch(err => {
reject(err.data)
})
})
};
/**
* 封装post请求 FormData方式
* @param url
* @param data
* @returns {Promise}
*/
export const postform=(url,data = {})=>{
return new Promise((resolve,reject) => {
instance
.post(url,data)
.then(res => {
resolve(res.data);
},err => {
reject(err.data)
})
})
}