0
const headers = new Headers();

headers.set(
  "Authorization",
   "Basic " + base64.encode(username + ":" + password)
);

fetch(url, { method: "GET", headers: headers })
  .then(res => {
    console.log("res", res.statusCode);
  });

res.send("success");

I am trying get a jpeg image file from an url using API URL. When I try to save the file, I am getting following error:

(node:18636) UnhandledPromiseRejectionWarning: FetchError: invalid json response body at [API url] reason: Unexpected token � in JSON at position 0

The url is working when using the Advance Rest Client chrome web application to display the image. But it is not working in node.js using above code. Can someone help me to sort this? That would be appreciated.

0xc14m1z
  • 3,675
  • 1
  • 14
  • 23
gopinath
  • 61
  • 1
  • 11

1 Answers1

1

you are using res.statusCode which is wrong, you should use res. status instead, Below is the working code.you can modify it as per your requirement.

const fetch = require('node-fetch');
    const fs =    require('fs')
    fetch('https://homepages.cae.wisc.edu/~ece533/images/airplane.png')
      .then(res => {
        if(res.status==200) {
          let contentType =res.headers.get('content-type')
          if(contentType=='image/png') {
            let stream  = fs.createWriteStream('./test.png')
             res.body.pipe(stream)
          }
         }
      })

;

Sandeep Patel
  • 4,815
  • 3
  • 21
  • 37
  • If your service returns byte format ,then conver it into base64 string and load by sub stract first till ; – LDS Nov 24 '19 at 08:32