首页 > 解决方案 > curl 可以获取 PDF,但 JavaScript 获取不能

问题描述

我有一个特定的 API 调用来获取 PDF,它与 curl 完美配合:

curl --location --request GET "https://app.hiddensite.com/api/v2/dn/jobs/export/INV-00181?format=pdf&document=pod&type=Delivery" --header "x-api-key: cfe5750a5d5114xxxxxxxxxxxx49dabb3e98c0cc63424cb014f" > a.pdf

但是,当我这样打电话时:

const r = await fetch('https://app.hiddensite.com/api/v2/dn/jobs/export/INV-00181?format=pdf&document=pod&type=Delivery',
    {
        method: 'GET',
        headers: {
            'x-api-key': 'cfe5750a5d5114xxxxxxxxxxxx49dabb3e98c0cc63424cb014f',
        },
    });
return r.text()

我得到一个大小略有不同的 PDF,几乎可以正确显示,但图形消失了,只有文本 - 即它在某种程度上有点畸形。无论是尝试 fs.writeFileSync() 还是只是 console.logging 输出和管道到文件,我都会得到这个。

知道是什么导致这些略有不同吗?

标签: javascriptnode.jsfetch

解决方案


PDF 并不完全是文本文件,因此尝试将其作为一个文件来阅读会在.text()其二进制部分(例如图形!)中引入错误。

你需要r.blob().


推荐阅读