vue 下载文件流和捕获后端返回的状态码和错误信息的方法
文件流下载需要注意的是 responseType: ‘blob’ ,否则下载的文件不能正确打开。但是当数据库返回400时,捕获不到error的错误信息,因为responseType设置了固定的返回格式。export function ExportWeiXinOrder(param){returnaxios({url: process.env.BASE_API+'/...
·
文件流下载需要注意的是 responseType: ‘blob’ ,否则下载的文件不能正确打开。但是当数据库返回400时,捕获不到error的错误信息,因为responseType设置了固定的返回格式。
export function ExportWeiXinOrder(param){
return axios({
url: process.env.BASE_API+'/order/Order/ExportWeiXinOrder',
timeout: 30000, // 请求超时时间10s
headers: {
//'Content-Type': 'application/x-zip-compressed',
'Authorization': token,
},
xhrFields: {
withCredentials: true
},
method:'post',
data:param,
responseType: 'blob',
});
}
//导出订单
ExportOrderSure() {
const vm = this;
var param = {
userWeiXinList: vm.weiXinIds,
};
ExportWeiXinOrder(param).then(x => { //
if (x.status == 200) {
vm.dialogExportOrder = false;
const content = x.data;
const blob = new Blob([content])
const fileName = '微信订单.zip'; //自定义下载文件的名字
if ('download' in document.createElement('a')) { // 非IE下载
const elink = document.createElement('a');
elink.download = fileName;
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
} else { // IE10+下载
navigator.msSaveBlob(blob, fileName);
}
}
}).catch(function(error){
console.log(error.response) //可获取错误的返回信息
if (error.response.status==400) {
}
}).finally(() => {
});
},
请求返回400,捕获后台返回的状态码和错误信息。
ExportWeiXinOrder(param)..catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
参考:https://segmentfault.com/q/1010000011190809/a-1020000011210688
更多推荐
已为社区贡献2条内容
所有评论(0)