我正在使用next.js。 我有一个第三方服务需要从中检索PDF文件。该服务需要一个API密钥,我不想在客户端公开该密钥。
这是我的文件
/api/getPDFFile.js ...
const options = {
method: 'GET',
encoding: 'binary',
headers: {
'Subscription-Key': process.env.GUIDE_STAR_CHARITY_CHECK_API_PDF_KEY,
'Content-Type': 'application/json',
},
rejectUnauthorized: false,
};
const binaryStream = await fetch(
'https://apidata.guidestar.org/charitycheckpdf/v1/pdf/26-4775012',
options
);
return res.status(200).send({body: { data: binaryStream}});
页面/getPDF.js
<button type="button" onClick={() => {
fetch('http://localhost:3000/api/guidestar/charitycheckpdf',
{
method: 'GET',
encoding: 'binary',
responseType: 'blob',
}).then(response => {
if (response.status !== 200) {
throw new Error('Sorry, I could not find that file.');
}
return response.blob();
}).then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.setAttribute('download', 'test.pdf');
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
})}}>Click to Download</button>
点击按钮下载文件,但当我打开它时,看到错误信息:“无法加载 PDF 文档。”