why am I getting favicon.ico when i am using findOne method for express params routes?

0

Issue

when i am using list.save() method a object other than customList name which is favicon.ico is also
saving as record in following cod, Why am i gatting favicon.ico as object.

app.get('/:listRoute',function (req,res) {

    const customList=(req.params.listRoute);
    List.findOne({name:customList }, function (err,result) {
        if (!err) {
            if (!result) {
                const list=new List({
                    name: customList,
                    items: defaultItems
                })
                list.save();
            } else {
                console.log(result);

                res.render('list', {
                    listTitle: result.name,
                    latestItems: result.items})
            }
            } 

    });
    })

Solution

When you visit a website (any URL on that website), a browser will typically also send a request to that same domain for /favicon.ico so see if the web site offers an icon to be a visual representation of the site.

Since you are using a wildcarded top level route:

app.get('/:listRoute', ...)

That will get hit by the request for /favicon.ico. Some other urls you also may need to watch out for being requested are: /robots.txt, /humans.txt, /sitemap.xml, /ads.txt.


There are a number of ways to work around this:

  1. Your wildcard route can first check req.url or req.params.listRoute to see if it’s something it should ignore.

  2. You can place other top level routes that you want to keep out of your wildcard route in a position before this route so they don’t end up in this one.

  3. Don’t use a top level wildcard route. Instead, use something like /list/:listRoute so it won’t automatically match any top level http request. Your use of a top level wildcarded route interferes with other future uses of your site and can create backwards compatibility going forward when you want to add other top level routes to your site. Imagine if sometime in the future, you want to add /contact or /login or /logout. Those all conflict with /:listRoute.

Answered By – jfriend00

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More