使用axios调用API下载pdf。我可以下载文件,但没有内容
await axios.post(URL,
JSON.stringify({ filter }),
{
headers: {
Authorization: token,
'Content-Type': 'application/json'
},
withCredentials: true
}
).then((response) => {
console.log(response);
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'expense.pdf');
document.body.appendChild(link);
link.click();
});
已经找到解决方案了!问题在于内容类型。我将其设置为 blob 并将其放在标题之外。以下代码现在工作正常。
await axios.post(URL,
JSON.stringify({ filter }),
{
headers: {
Authorization: token
},
responseType: 'blob',
withCredentials: true
}
).then((response) => {
console.log(response);
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'expense.pdf');
document.body.appendChild(link);
link.click();
});