在expressjs中将二进制响应转换为pdf

问题描述 投票:0回答:1

我正在尝试使用

Browserless PDF API
,为此我编写了以下代码:

// my server located on localhost:3000
app.get("/api/pdf", async (request, response) => {
    try {
        const { data } = await axios.post("http://localhost:3001/pdf", {
            url: "https://www.google.com/",
        })

        response.setHeader("content-type", "application/pdf")
        response.contentType("application/pdf")
        response.send(Buffer.from(data, "binary"))
    } catch (error) {
        console.log(error.message)
    }
})

在浏览器中它看起来像这样: enter image description here

但是如果我满足同等的卷曲请求

// Browserless API located on localhost:3001
curl -X POST  \
  http://localhost:3001/pdf \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/json' \
  -d '{
  "url": "https://google.com/"
}'  --output 'file.pdf'


  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 49148    0 49114  100    34  38039     26  0:00:01  0:00:01 --:--:-- 38040

它看起来像这样

enter image description here

我的代码有什么问题吗?

最小可重现示例 https://stackblitz.com/edit/node-hw2mex?file=index.js

javascript express pdf
1个回答
0
投票

我应该在

responseType: "arraybuffer"
配置对象中添加
axios.post

app.get("/api/pdf", async (request, response) => {
    try {
        const { data } = await axios.post(
            "http://localhost:3001/pdf",
            {
                url: "https://www.google.com/",
            },
            {
                responseType: "arraybuffer",
            },
        )

        response.setHeader("content-type", "application/pdf")
        response.contentType("application/pdf")
        response.send(Buffer.from(data, "binary"))
    } catch (error) {
        console.log(error.message)
    }
})

PS:感谢@Jaromanda X 的调查

© www.soinside.com 2019 - 2024. All rights reserved.