我正在使用 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 文档失败”。
@brc-dd 在这个问题上救了我。我必须添加的一件事是动态生成的链接元素(参见代码中的
var link
),一旦我们从 API 获得文件数据,它就会自行点击。这对于获得一致的下载非常重要(我之前没有得到)。我的页面代码创建了下载文件的链接,如下所示:
链接调用的本地 NextJs API 端点(/api/qualtrics/retrieve-file)如下所示: