PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

[FIXED] How can I store or obtain the inaccurate route that was searched for?

 October 21, 2022     backend, express, node.js     No comments   

Issue

In this case, how could I save the /india route in a variable in the router? app.get(‘*’, function(req, res){ //Save rute here; }


Solution

If you just want to log the bad route to a file, you can do something like this. Just make this is the last route you define so that all other routes get a chance to match before it does:

app.get("*", (req, res) => {
    // log the unhandled route
    fs.appendFile("bad-routes.txt", req.path + "\n", (err) => {
        if (err) {
            console.log(`Error attempting to append ${req.path} to bad-routes.txt`);
        }
    });
    res.sendStatus(404);
});

Note, in this list, you will probably find things that crawlers (not users) are also probing your site for.

The above logs only GET requests. If you want to log for all http verbs, you could do this:

app.use((req, res) => {
    // log the unhandled route
    fs.appendFile("bad-routes.txt", `${req.method}: ${req.path}\n`, (err) => {
        if (err) {
            console.log(`Error attempting to append ${req.path} to bad-routes.txt`);
        }
    });
    res.sendStatus(404);
});

It's possible that fs.appendFile() could have some race conditions if multiple requests were both trying to log. In that case, it would be safer to use a shared stream which will safely sequence the writes:

let logUnhandledStream;

app.use((req, res) => {
    // log the unhandled route
    if (!logUnhandledStream) {
        logUnhandledStream = fs.createWriteStream("bad-routes.txt", { flags: "a" });
        logUnhandledStream.on('error', err => {
            console.log(`Error attempting to log to bad-routes.txt`, err);
        });
    }
    logUnhandledStream.write(`${req.method}: ${req.path}\n`);
    res.sendStatus(404);
});


Answered By - jfriend00
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing