Akash Dathan Akash Dathan - 24 days ago 8
Node.js Question

NodeJs request.get() function not working while the url is accessible from the browser

I am using the

request
npm module.I want to retrieve an image from a url. The request.get(url) function is returning me a '400 Bad Request', whereas the image is accessible from the browser.

The url i am hitting is :
http://indiatribune.com/wp-content/uploads/2017/09/health.jpg

Answer Source

You could try to add some headers:

const request = require('request');
request.get({
    url: 'http://indiatribune.com/wp-content/uploads/2017/09/health.jpg',
    headers: {

        Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'en-GB,en;q=0.8,en-US;q=0.6,hu;q=0.4',
        'Cache-Control': 'max-age=0',
        Connection: 'keep-alive',
        Host: 'indiatribune.com',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36',

    },
}, (err, response, data) => {
    console.log(response, data);
});

The User-Agent seems to be enough.