首页 > 解决方案 > 如何从 nodejs 获取 pdf 并使用 vuejs 在新的浏览器选项卡中显示

问题描述

我在 vuejs 模板中有一个按钮。

单击此按钮时从我的节点后端请求 pdf。

接下来,我有一个代码来显示下载到新的 chrome 浏览器选项卡中的 pdf。

我的问题是我总是得到 tbhis 错误:“错误未能加载 pdf 文档”。这里有什么问题?

//nodejs

const express = require("express");
const router = express.Router();
const axios = require("axios");

router.post("/getPDF", async (req, res) => {
  const url = req.body.url;
  const dados = await axios(url, {
    headers: {
      authorization: "Guest",
      "Access-Control-Allow-Origin": "*",
    },
    method: "GET",
    responseType: "blob", //Force to receive data in a Blob Format
  });
  res.contentType("application/pdf");
  res.send({ data: dados.data });
});

//vuejs

<template>
...
<v-btn
   @click.stop="fVisualizarBula(item[header.value])"></v-btn>
...
</template>

export default {
...
methods:{
async fVisualizarBula(pIdAnexo) {
      const filePDFURL = `https://samplesite/api/consulta/medicamentos/arquivo/bula/parecer/${pIdAnexo}/?Authorization=`;
      try {
        const response = await ServicePDF.getPDF({ url: filePDFURL });
        //Create a Blob from the PDF Stream
        const file = new Blob([response.data], {
          type: "application/pdf",
        });
        console.log(file)
        //Build a URL from the file
        const fileURL = URL.createObjectURL(file);
        //Open the URL on new Window
        window.open(
          fileURL,
          "_blank",
          "toolbar=yes,scrollbars=yes,resizable=yes,top=10,left=10,width=900,height=600"
        );
      } catch (error) {
        console.log(error);
      }
    }
}

//console.log(file) 示例

Blob {size: 1110659, type: "application/pdf"}
size: 1110659
type: "application/pdf"
__proto__: Blob
arrayBuffer: ƒ arrayBuffer()
size: 1110659
slice: ƒ slice()
stream: ƒ stream()
text: ƒ text()
arguments: (...)
caller: (...)
length: 0
name: "text"
__proto__: ƒ ()
[[Scopes]]: Scopes[0]
type: (...)
constructor: ƒ Blob()
Symbol(Symbol.toStringTag): "Blob"
get size: ƒ size()
get type: ƒ type()
__proto__: Object

标签: javascripthtmlnode.jsvue.js

解决方案


推荐阅读