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.

1 Answer 1

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

;

Sign up to request clarification or add additional context in comments.

1 Comment

If your service returns byte format ,then conver it into base64 string and load by sub stract first till ;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.