0

I'm sending a request to an api to get back a png file. if I console.log that file, it starts with this: �PNG → IHDR☻X☻♠� etc.etc.

When I try to encode it in base64, to use it later in an img element, the encoded string starts with /VBOR instead of iVBOR and it's just different than what the correct format should be.

This is my code:

var axios = require("axios").default;
var btoa = require("btoa")

var options = {
  method: 'POST',
  url: 'https://qrcode3.p.rapidapi.com/qrcode/text',
  headers: {
    'content-type': 'application/json',
    'x-rapidapi-host': 'qrcode3.p.rapidapi.com',
    'x-rapidapi-key': '*****'
  },
  data: {
    data: 'https://linqr.app',
    image: {uri: 'icon://appstore', modules: true},
    style: {
      module: {color: 'black', shape: 'default'},
      inner_eye: {shape: 'default'},
      outer_eye: {shape: 'default'},
      background: {}
    },
    size: {width: 600, quiet_zone: 4, error_correction: 'M'},
    output: {filename: 'qrcode', format: 'png'}
  }
};

axios.request(options).then(function (response) {
    console.log(btoa(response.data));
}).catch(function (error) {
    console.error(error);
});
  • `�` could be anything ... can you `console.log(response.data.charCodeAt(0))` - it should be 137 I beleive – Bravo Mar 03 '22 at 00:37
  • @Bravo sure, the result of console.log(response.data.charCodeAt(0)) is 65533 and of console.log(btoa(response.data).charCodeAt(0)) is 47 – Matteo Barberis Mar 03 '22 at 00:41
  • I didn't want btoa - but 65533 is not 137 - the issue is the server is not sending the PNG correctly - or perhaps axios is mangling it, not sure which - for the latter, try the solution at https://stackoverflow.com/questions/40211246/encoding-issue-with-axios - i.e. add `responseType: 'arraybuffer', responseEncoding: 'binary'` to your `var options` – Bravo Mar 03 '22 at 00:50
  • @Bravo that didn't work because as soon as I add responseType: 'arraybuffer', responseEncoding: 'binary', then I get the error: Request failed with status code 422 However I found a solution online and by adding responseType: 'stream' and writing this then I'm able to get the right string: const chunks = linqr_response.data .pipe(new PassThrough({encoding:'base64'})); let str = ''; for await (let chunk of chunks) { str += chunk; } console.log(str); No idea why this works and the other method doesn't but who knows – Matteo Barberis Mar 03 '22 at 01:09

0 Answers0