React+Axios调用Express+PDFKit生成PDF后打开显示空白
React+Axios下载Express生成的PDF空白问题解决
核心问题及修复方案
1. Express端PDF流处理顺序错误
代码中先调用doc.end()再执行doc.pipe(res),会导致PDF内容还未写入响应就终止了文档流,返回的PDF缺少实际内容,打开后显示空白。
修正后Express代码:
import { Request, Response } from "express" import PDFDocument from 'pdfkit'; export const createPDF = async ( req: invoiceGeneratorRequest, res: Response ) => { try { res.writeHead(200, { 'Content-Type': 'application/pdf', 'Content-Disposition': 'attachment; filename=test.pdf' }); let doc = new PDFDocument({ size: 'A4', margin: 50 }); // 先将文档流绑定到响应对象 doc.pipe(res); doc.fontSize(12); doc.text('PDFKit is simple', 10, 30, { align: 'center', width: 200 }); // 最后结束文档流 doc.end(); } catch (error) { console.error("Error creating PDF", error) res.status(500).send("Error creating PDF") } }
2. React端Axios请求配置位置错误
Axios的post方法参数格式为axios.post(url, data, config),你将responseType和headers错误放在了第二个参数(请求体)的位置,导致配置未生效,无法正确接收二进制PDF数据。同时请求的Content-Type设置为application/pdf不符合POST请求的语义,应根据发送的数据类型调整(比如JSON数据用application/json)。
修正后React代码:
import axios from 'axios'; import download from 'downloadjs'; export const downloadInvoiceApi = async (values) => { await axios.post( `${baseUrl}/invoice-generator/create-pdf`, values, // 传入POST请求的实际参数 { responseType: "arraybuffer", headers: { "Content-Type": "application/json" } } ) .then((response) => { download(response.data, "file.pdf", response.headers['content-type']); }); };
内容的提问来源于stack exchange,提问作者monty_lennie
相关产品推荐
相关产品推荐

