0

I wrote a function to do a GET request that retrieves a pdf file as the response, so i call the getshippinglabel function, and then base64 encode the answer and save it to a .txt file, the problem is that when i try to decode my .txt all i got is a blank pdf

This is the code block where i call my function and send it to the base64 txt

   shippingLabelPdf = await getShippingLabel( shippingId, Token);


           shippingLabel = Buffer.from(shippingLabelPdf).toString("base64");
            fs.writeFile('./guia.txt', shippingLabelPdf, err => {
              if (err) {
               console.error(err);
               }
             
            });


and this is the function itself

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)})

}

i have been refering to this question and this article

meaning that i have used: encode:'binary/null' responseType:'blob/arraybuffer' but any combination works at all

2 Answers2

0

You should try to move your response to blob and encode to null, so this way Buffer could take correctly the parameter and correctly encode it

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)})
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
0

Your resonseType is correct but it is placed inside the params when it should be outside.

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)})

}
Agohof
  • 31
  • 3