NodeJS 为什么我的Axios请求返回一个空白的PDF?

c8ib6hqw  于 2023-03-22  发布在  Node.js
关注(0)|答案(1)|浏览(291)

我编写了一个函数来执行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)})

}

this questionthis article
意思是我用过:encode:'binary/null' responseType:'blob/arraybuffer'但任何组合都有效

xuo3flqw

xuo3flqw1#

您应该尝试将响应移动到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)})

}

相关问题