【发布时间】:2017-09-27 02:07:33
【问题描述】:
为了强制从服务器下载 PDF,我尝试使用 axios 和本机 xhr 对象。原因是我必须发送 post 请求,因为我向服务器传递了太多数据,所以带有简单链接的选项(如 site.ru/download-pdf 对我不起作用)。
即使我最终设法用 Xhr 做到了这一点,我仍然不知道为什么 axios 方式不起作用。
这是我使用 xhr 执行此操作的方法,它适用于我:
let xhr = new XMLHttpRequest()
xhr.open('POST', Vue.config.baseUrl + `order-results/${id}/export-pdf`, true)
xhr.setRequestHeader("Authorization", 'Bearer ' + this.token())
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xhr.responseType = 'arraybuffer'
xhr.onload = function(e) {
if (this.status === 200) {
let blob = new Blob([this.response], { type:"application/pdf" })
let link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = 'Results.pdf'
link.click()
}
};
xhr.send("data=" + data);
这是“axios-way”,我实际上得到了页数正确的 PDF,但它们都是空的:
axios.post(`order-results/${id}/export-pdf`, {
data,
responseType: 'arraybuffer'
}).then((response) => {
let blob = new Blob([response.data], { type:"application/pdf" })
let link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = 'Results.pdf'
link.click()
})
Axios 已配置为发送授权令牌。
我将Application/x-www-form-urlencoded 放在 xhr 中,否则我无法在服务器端获取数据。
即使 xhr 有效,我还是更喜欢使用 axios,因为我到处都在使用它,而且我只是好奇我做错了什么。我尝试了不同的解决方案,只有原生 xhr 完成了这项工作。
【问题讨论】:
标签: javascript ajax pdf xmlhttprequest axios