为何Axios请求返回空白PDF?Node.js运单标签获取问题
解决获取PDF运单标签后解码为空白PDF的问题
问题情况
我编写了一个GET请求函数以获取PDF格式的运单标签,调用getShippingLabel函数后将结果转Base64编码保存到.txt文件,但解码该文件后得到的是空白PDF。尝试过设置encode:'binary/null'、responseType:'blob/arraybuffer'等组合,均无效。
原调用代码:
shippingLabelPdf = await getShippingLabel(shippingId, Token); shippingLabel = Buffer.from(shippingLabelPdf).toString("base64"); fs.writeFile('./guia.txt', shippingLabelPdf, err => { if (err) { console.error(err); } });
原函数代码:
async function getShippingLabel(shippingId, Token){ let axiosConfig = { method:'get', maxBodyLength: Infinity, headers: { 'Authorization': 'Bearer ' + Token, "Content-Type": "application/pdf" }, params: { "shipment_ids": shippingId, "responseType":"arraybuffer", } }; var meliUrl = "https://api.mercadolibre.com/shipment_labels"; return axios(meliUrl, axiosConfig).then(response => response.data).catch(function (error) { console.log( error.response.data)}) }
问题根源
- responseType参数位置错误:axios的
responseType是请求配置的顶层参数,不能放在params中,这会导致axios无法正确解析二进制PDF数据,最终拿到乱码或空内容。 - 写入文件用错变量:代码中把原始的
shippingLabelPdf写入了文件,但实际应该写入Base64编码后的shippingLabel变量。 - 请求头设置不当:
Content-Type用于标识发送的请求体格式,这里是GET请求获取PDF,应该用Accept头告知服务端需要PDF格式,而非设置Content-Type。
修正后的代码
修正后的getShippingLabel函数
async function getShippingLabel(shippingId, Token){ let axiosConfig = { method:'get', maxBodyLength: Infinity, responseType: 'arraybuffer', // 移到顶层配置 headers: { 'Authorization': 'Bearer ' + Token, 'Accept': 'application/pdf' // 改用Accept头指定接收PDF }, params: { "shipment_ids": shippingId // 移除params中的responseType } }; var meliUrl = "https://api.mercadolibre.com/shipment_labels"; try { const response = await axios(meliUrl, axiosConfig); return response.data; } catch (error) { console.error(error.response?.data || error.message); throw error; // 抛出错误让调用方处理 } }
修正后的调用代码
shippingLabelPdf = await getShippingLabel(shippingId, Token); // 对二进制PDF数据进行Base64编码 shippingLabel = Buffer.from(shippingLabelPdf).toString("base64"); // 写入编码后的变量到文件 fs.writeFile('./guia.txt', shippingLabel, err => { if (err) { console.error(err); } else { console.log("Base64编码的PDF已保存"); } });
额外说明
如果后续需要解码还原PDF,可以读取txt文件的Base64内容,再转成Buffer写入PDF文件:
const fs = require('fs'); const base64Content = fs.readFileSync('./guia.txt', 'utf8'); const pdfBuffer = Buffer.from(base64Content, 'base64'); fs.writeFileSync('./guia.pdf', pdfBuffer);
内容的提问来源于stack exchange,提问作者Miguel Castillo B
相关产品推荐
相关产品推荐

