我无法在新 window 中显示从服务器获取的 pdf 文件

i can't display pdf file getting from server in new window

我的服务器中有 pdf,我将其发送给客户端。我进入 blob 并从中执行 URL,我用它在新的 window 中打开。它显示的页面是这样的

%PDF-1.4
1 0 obj
<<
/Title (��)
/Creator (��)
/Producer (���Q�t� �5�.�5�.�1)
/CreationDate (D:20211128130647)
>>
endobj
2 0 obj
<<
/Type /Catalog
/Pages 3 0 R
>>
endobj
4 0 obj .....

我的代码

    axios
  .post(DOMENNAME + "/API/getPdf", { responseType: 'blob', body: id })
  .then((res) => {
     const url = window.URL.createObjectURL(new Blob([res.data],{type: "application/pdf"}));
       window.open(url);
     })
   .catch((e) => {
      console.log(e.message);
      dispatch(getPdfFailure());
    });

服务器路径

    module.exports.taskGetPdf=(req,res)=>{
  res.set("Access-Control-Allow-Origin", "*");
  res.set("Access-Control-Allow-Methods", "GET, OPTIONS");
  res.set("Access-Control-Allow-Headers", "Content-Type");

  res.sendFile("result38555.pdf", { root: __dirname })

问题出在请求方法中,我应该改用 GET 请求 POST。然后我改变了一切正常。

export const getPdf = (id) => {
  return (dispatch) => {
    axios
      .get(DOMENNAME + "/API/getPdf" + "/" + id, {
        responseType: "blob",
      })
      .then((res) => {
        let blob = new Blob([res.data], { type: "application/pdf" });
        const url = URL.createObjectURL(blob);
        let newWin = window.open();
        newWin.location.href = url;
      })
      .catch((e) => {
        console.log(e.message);
        dispatch(getPdfFailure());
      });
  };
};

服务器

module.exports.taskGetPdf = (req, res) => {
  res.set("Access-Control-Allow-Origin", "*");
  res.set("Access-Control-Allow-Methods", "GET, OPTIONS");
  res.set("Access-Control-Allow-Headers", "Content-Type");

  console.log(req.params.id);
  res.sendFile(`result${req.params.id}.pdf`, { root: __dirname });
};