一、Axios下載Excel
Axios是一個可以使用Promise對象實現HTTP客戶端的JS庫。下載Excel最常用的一種方式就是將後端返回的二進位流轉換成Blob對象,然後再通過URL.createObjectURL方法生成下載鏈接,最後觸發a標籤的click事件進行下載。
代碼示例:
axios.get(url, {
responseType: 'blob'
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.xlsx');
document.body.appendChild(link);
link.click();
});
二、下載 PDF 文件
如下示例所示,在axios下載PDF文件的過程中,在responseType配置項中設置’arraybuffer’,然後對response.data進行Blob的實例化。
代碼示例:
axios.get(url, {
responseType: 'arraybuffer'
}).then(response => {
const blob = new Blob([response.data], { type: 'application/pdf' });
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();
});
三、Axios怎麼讀
在使用Axios進行讀取數據時,需要使用到axios.get、axios.post等請求方式。針對讀取數據,axios.get是使用頻率最高的方式。
代碼示例:
axios.get('/api/data')
.then(response => {
console.log(response.data);
}).catch(error => {
console.error(error);
})
四、Axios官網
Axios GitHub官網上有詳細的文檔和示例,可以方便地學習和使用此JS庫。
官網地址:https://github.com/axios/axios
五、Axios跨域
在進行跨域請求時,需要後端同意響應特定的HTTP響應頭。
後端配置示例:
// 允許跨域請求的域名和埠
response.setHeader('Access-Control-Allow-Origin', '*');
// 允許跨域請求的HTTP方法
response.setHeader('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
// 允許跨域請求的HTTP頭
response.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
然後通過axios的請求方式進行跨域請求,示例代碼如下:
axios.get('http://example.com/resource', {
headers: { Authorization: 'Bearer ' + token }
}).then(response => {
console.log(response.data);
}).catch(error => {
console.error(error);
});
六、美國Axios網站
美國的axios網站是一家總部位於紐約市的新聞網站,提供美國政治、商業和技術領域深入報道。
網址:https://www.axios.com/
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/286208.html
微信掃一掃
支付寶掃一掃