[英]How to download a file from json api backend using vue?
我有一個帶有vue.js前端的rails api后端和簡單的jwt身份驗證。
所以,有2台服務器localhost:8080
和3000
如何從與json響應相關的鏈接下載pdf文件。
{
"id": 25,
"title": "test",
"export_pdf": "http://localhost:3000/api/v1/export/25.pdf",
}
使用以下代碼,我收到unauthorized
錯誤,因為localhost:3000
上沒有localstorage
<li><a :href="project.export_pdf" download='report'>Export as PDF</a></li>
-
我也在使用axios
如果我做這樣的事情
exportPdf: (url) => {
return axios.get(url, auth.getHeader())
}
它將返回以下內容
Object {data: "gibberish text", status: 200, statusText: "OK", headers: Object, config: Object…}
您應該更改blob
的responseType
,以便axios
正確解析數據。 您的后端必須在此文件中返回標題content-disposition: attachment
。
另外,我認為您無法通過Ajax下載它。 我無法理解你對錨的理由,LocalStorage在那里改變了什么?
請嘗試以下:
<a href="project.export_pdf" target="_blank">Export to PDF</a>
我決定在下載鏈接的末尾添加下載令牌。
所以,現在我可以做到以下幾點
http://localhost:3000/api/v1/projects/28/export?tkn=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
然后,在我的前端
<li><a :href="dllink" download='report.pdf'>Export as PDF</a></li>
-
dllink () {
let tkn = window.localStorage.getItem('tkn')
return `${this.project.export_pdf}?tkn=${tkn}`
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.