PDF 打开时是空白的

bp1*_*123 2 javascript blob express reactjs filesaver.js

我已经在这里待了几个小时,但我什么也没有得到。我正在尝试从我的服务器下载 PDF 文件。我目前正在本地主机上运行它。当我打开 PDF 时,PDF 是一个白色的空白页。有人可以让我知道我错过了什么。我已经检查了保存在服务器上的 PDF,它很好。

应用程序 - 反应,表达。

NPM - Axios,文件保护程序,html-pdf

小路 - Front end React

.then(() =>
  axios.get(
    'http://localhost:3000/retailers/fetch/pdf',
    {
      headers: {
        'Content-type': 'application/json',
        'x-auth-token': this.props.token
      }
    },
    { responseType: 'blob' }
  )
)
.then((res) => {
  console.log('dd', res);
  const pdfBlob = new Blob([res.data], { type: 'application/pdf' });

  saveAs(pdfBlob, 'newPdf.pdf');
});
Run Code Online (Sandbox Code Playgroud)

小路 - Backend express

const options = {
  root: path.join(__dirname, '../'),
  dotfiles: 'deny',
  headers: {
    'x-timestamp': Date.now(),
    'x-sent': true
  }
};

var fileName = 'test.pdf';
res.sendFile(fileName, options, function (err) {
  if (err) {
    console.log('err', err);

    next(err);
  }
});
Run Code Online (Sandbox Code Playgroud)

bp1*_*123 6

所以答案很简单。responseType: 'blob'是在错误的地方。

axios.get(
  'http://localhost:3000/retailers/fetch/pdf',
  {
    headers: {
      'Content-type': 'application/json',
      'x-auth-token': this.props.token
    },
    responseType: 'blob'
  }
)
Run Code Online (Sandbox Code Playgroud)