相关疑难解决方法(0)

如何使用 API 路由在 Next.js 上下载文件

我正在使用 next.js。我有一个第 3 方服务,我需要从中检索 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}}); 


Run Code Online (Sandbox Code Playgroud)

页面/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 …
Run Code Online (Sandbox Code Playgroud)

download next.js

2
推荐指数
1
解决办法
810
查看次数

标签 统计

download ×1

next.js ×1