我正在尝试使用
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)
}
})
但是如果我满足同等的卷曲请求
// 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
它看起来像这样
我的代码有什么问题吗?
最小可重现示例 https://stackblitz.com/edit/node-hw2mex?file=index.js
我应该在
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 的调查