通过ES6的Promise来对axios做封装,让网络请求更方便。
- src下创建common/axios.js
import axios from 'axios';
axios.defaults.baseURL='/api' //此路径为配置代理服务器时的代理路径
export default {
get(options){
return new Promise((resolve,reject) => {
axios({
method: 'get',
url: options.url,
data: options.data,
headers: {
Accept: 'application/json','Content-Type': 'application/json; charset=utf-8',
withCredentials: true,
},
//默认json格式,如果是下载文件,需要传 responseType:'blob'
responseType: (options.responseType == null || options.responseType == '') ? 'json' : options.responseType
}).then(response => {
if (response.status == 200) {
//根据实际情况进行更改
resolve(response)
}else{
reject(response)
}
})
})
},
post(options){
return new Promise((resolve,reject) => {
axios({
method: 'post',
url: options.url,
data: options.data,
headers: {
Accept: 'application/json','Content-Type': 'application/json; charset=utf-8',
withCredentials: true,
},
//默认json格式,如果是下载文件,需要传 responseType:'blob'
responseType: (options.responseType == null || options.responseType == '') ? 'json' : options.responseType
}).then(response => {
if (response.status == 200) {
//根据实际情况进行更改
resolve(response)
}else{
reject(response)
}
})
})
}
}
- main.js中导入并挂在Vue原型
import Axios from "@/common/axios" //路径根据实际路径做修改
Vue.prototype.$axios = Axios;
- 进行网络请求
let option = {
data : {},
url : this.$api.fileDownload,
responseType : 'blob'
}
this.$axios.post(option).then(res => {
//数据处理
});