Home > Software engineering >  How can I store or obtain the inaccurate route that was searched for?
How can I store or obtain the inaccurate route that was searched for?

Time:10-18

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

CodePudding user response:

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);
});
  • Related