我编写了一个函数来执行 GET 请求,检索 pdf 文件作为响应, 所以我调用 getshippinglabel 函数,然后对答案进行 Base64 编码并将其保存到 .txt 文件中,问题是当我尝试解码 .txt 时,我得到的只是一个空白的 pdf
这是我调用函数并将其发送到 base64 txt 的代码块
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)})
}
这意味着我已经使用了:encode:'binary/null'responseType:'blob/arraybuffer'但任何组合都可以工作
您应该尝试将响应移至 blob 并编码为 null,这样 Buffer 就可以正确获取参数并对其进行正确编码
async function getShippingLabel(shippingId, Token) {
let axiosConfig = {
method:'get',
maxBodyLength: Infinity,
headers: {
'Authorization': 'Bearer ' + Token,
"Content-Type": "application/pdf"
}, params: {
"shipment_ids": shippingId,
"responseType":"blob",
"encode":"null"
}
};
var meliUrl = "https://api.mercadolibre.com/shipment_labels";
return axios(meliUrl, axiosConfig).then(response => response.data).catch(function (error) { console.log( error.response.data)})
}
您的 resonseType 是正确的,但它被放置在参数内部,而它应该位于外部。
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)})
}