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

Postman中PDF响应显示异常,浏览器打开正常问题求助

问题场景

通过POST接口返回PDF文件时,Postman中查看响应会出现内容缺失,且重复请求时空白位置会变化,但在浏览器中打开该PDF显示完全正常。相关Node.js路由代码如下:

router.post('/getPdf', auth.authenticateToken, function (req, res) {
    const orderDetails = req.body;
    const pdfPath = './generated_pdf/' + orderDetails.uuid + '.pdf';
    if (fs.existsSync(pdfPath)) {
        res.contentType("application/pdf");
        fs.createReadStream(pdfPath).pipe(res);
    }
    else {
        var productDetailsReport = JSON.parse(orderDetails.productDetails);
        ejs.renderFile(path.join(__dirname, '', "report.ejs"), { productDetails: productDetailsReport, name: orderDetails.name, email: orderDetails.email, contactNumber: orderDetails.contactNumber, paymentMethod: orderDetails.paymentMethod, totalAmount: orderDetails.totalAmount }, (err, results) => {
            if (err) {
                console.log(err);
                return res.status(500).json(err);
            }
            else {
                pdf.create(results).toFile('./generated_pdf/' + orderDetails.uuid + ".pdf", function (err, data) {
                    if (err) {
                        console.log(err);
                        return res.status(500).json(err);
                    }
                    else {
                        res.contentType("application/pdf");
                        fs.createReadStream(pdfPath).pipe(res);
                    }
                })
            }
        })
    }
})
可能的原因及解决方案
  • 流传输未正确处理完整生命周期
    直接使用fs.createReadStream().pipe(res)时,若未确保流完全传输完毕就结束响应,Postman的响应解析逻辑可能会提前截断内容(浏览器的处理逻辑更容错)。建议改用Express内置的res.sendFile方法,它会自动处理文件读取、传输及响应结束的完整流程,比手动pipe更可靠:

    // 替换原有pipe的代码
    if (fs.existsSync(pdfPath)) {
      res.sendFile(pdfPath, { 
        headers: { 'Content-Type': 'application/pdf' } 
      }, (err) => {
        if (err) {
          console.log(err);
          res.status(500).json(err);
        }
      });
    }
    // 生成PDF后的回调中也做同样替换
    
  • PDF文件写入未完成即读取
    pdf.create(...).toFile()的回调触发仅表示写入请求已提交,而非文件完全写入磁盘(受文件系统缓存影响)。此时读取文件会拿到不完整的内容,导致重复请求时空白位置随机变化。可以改用fs.readFile读取完整文件内容后再发送:

    // 生成PDF后的回调内替换为:
    fs.readFile(pdfPath, (err, data) => {
      if (err) {
        console.log(err);
        return res.status(500).json(err);
      }
      res.contentType("application/pdf");
      res.send(data);
    });
    
  • Postman内置PDF预览器bug
    若上述修改后仍存在问题,可尝试在Postman中点击「Save Response」下载PDF文件,打开本地文件查看是否完整。如果本地文件正常,说明是Postman预览器的渲染问题,无需修改代码。

内容的提问来源于stack exchange,提问作者Dulan Jay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 09:25:55