[英]Error when trying to download tweets from Twitter API to Mongoose
[英]Authorization failed error when trying to download from an anchor tag
当我在 PostMan 中尝试时,我可以通过将令牌添加到标题来下载文件。 我找不到在标题上添加令牌的方法。 那是应该在前端还是后端?
反应js
<a
href={process.env.REACT_APP_BACKEND_URL +`/files/download/${props.id}`}
rel="noreferrer"
target="_blank"
download
className="download-link"
>
Download File
</a>
快递js:
router.get('/download/:fid', async (req, res, next) => {
const fileId = req.params.fid;
let filePost;
try {
filePost = await File.findById(fileId);
} catch (err) {
return next(new HttpError("Error", 500));
}
console.log(filePost.file);
res.download(filePost.file);
);
使用纯 HTML( <a>
锚点或<form>
)下载资源只会产生带有“标准”标头(如Accept-Language
或Accept-Encoding
)的请求,而不是带有令牌标头的请求。 因此,您尝试使用纯 HTML 是不可能的。
你可以做什么它使用 Javascript 函数fetch
发出请求,并将响应转换为使用URL.createObjectURL
的下载 URL。 然后可以将此下载 URL 分配给用户可以单击的锚元素。
fetch(`${process.env.REACT_APP_BACKEND_URL}/files/download/${props.id}`,
{headers: {...}})
.then(function(response) {
document.getElementById("anchor").download =
response.headers.get("Content-Disposition").match(/filename="(.*)")/)[1];
return response.blob();
})
.then(function(blob) {
document.getElementById("anchor").href = URL.createObjectURL(blob);
});
您需要使用Http Client
在标头中发送令牌。
const handleDownload = async () => {
const res = await fetch(`${process.env.REACT_APP_BACKEND_URL}/files/download/${props.id}`, {
headers: {
token: '<your token>'
}
});
const json = await res.json();
console.log(json.data);
};
<a
onClick={handleDownload}
rel="noreferrer"
target="_blank"
download
className="download-link"
>
Download File
</a>
我强烈建议您将标签转换a
button
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.