You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express.js调用Browserless PDF API返回PDF异常问题排查

问题:Browserless PDF API生成的PDF在浏览器显示异常,curl请求却正常

我用Browserless PDF API写了一段接口代码,部署在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)
    }
})

现在遇到的问题是:直接在浏览器访问/api/pdf接口时,PDF显示异常;但用相同参数通过curl调用Browserless的localhost:3001/pdf接口时,生成的PDF是正常的。


问题原因与解决方案

问题出在axios的默认响应处理逻辑上:axios会自动把响应数据解析成字符串,而PDF是二进制文件,字符串解析过程中会破坏原始二进制数据,导致最终传给浏览器的PDF文件损坏。

要解决这个问题,只需在axios请求中添加responseType: 'arraybuffer'配置,让axios直接返回二进制的ArrayBuffer,避免数据解析错误。

修改后的代码如下:

app.get("/api/pdf", async (request, response) => {
    try {
        // 添加responseType配置,获取原始二进制数据
        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")
        // 直接将ArrayBuffer转为Buffer返回
        response.send(Buffer.from(data))
    } catch (error) {
        console.log(error.message)
    }
})

修改说明

  • responseType: 'arraybuffer':告诉axios不要对响应数据做字符串解析,直接保留二进制格式
  • 移除Buffer.from(data, "binary")中的"binary"编码参数,因为ArrayBuffer本身就是二进制数据,直接转Buffer即可

这样修改后,浏览器访问接口就能正常加载并显示PDF文件了。

内容的提问来源于stack exchange,提问作者Pavel Perevezencev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 18:39:56