简体   繁体   中英

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

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.

Use download module . It's pretty simple.

const fs = require('fs');
const download = require('download');

download('http://indiatribune.com/wp-content/uploads/2017/09/health.jpg').pipe(fs.createWriteStream('foo.jpg'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM