Node Express “favicon.ico” not found error

别说谁变了你拦得住时间么 提交于 2021-02-18 18:15:54

问题


I'm trying to download a photo through a URL passed as a query string using Express, but every time I try to use it, I get Error: Invalid URI "favicon.ico" Is there a way I can get my browser to stop requesting a favicon? For downloading images, I'm using the image-downloader package (NPM page)

Code:

app.get('/:url', (req, res) => {
let url = req.params.url;
const options = {
    url: url,
    dest: /path'
};
download.image(options)
    .then(({ filename, image }) => {
        console.log('File saved to ', filename);
})
    .catch((err) => {
        console.log(err);
    });
res.send("Done");

});


回答1:


It's probably easiest to just make a route for favicon.ico in your server.

app.get('/favico.ico', (req, res) => {
    res.sendStatus(404);
});

Of course, you could actually send a valid icon too if you wanted, but this will at least keep your Express server from showing an error.

FYI, this has nothing to do with the image-downloader. This has to do with the browser requesting a favico.ico icon that it uses to show in the URL bar (and some other places in the browser UI). If your server returns a 404 for favicon.ico, the browser will use a generic icon in its UI.

If you want to make yourself a simple favico.ico, you can go here and it will help you generate one and then you can change the above route to:

app.get('/favico.ico', (req, res) => {
    res.sendFile("myfavico.ico");
});



回答2:


Try using another package like request module. I believe it got this type of things handled.

var fs = require('fs'),
request = require('request');

var download = function(uri, filename, callback){
  request.head(uri, function(err, res, body){
    console.log('content-type:', res.headers['content-type']);
    console.log('content-length:', res.headers['content-length']);

    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};

download('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){
  console.log('done');
});


来源:https://stackoverflow.com/questions/53253723/node-express-favicon-ico-not-found-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!