0

Here is a question I have concerning a Node.js app of mine (working with Express) on Heroku. I want to handle unknown URL. More precisely:

If I look at this URL in a browser: https://myapp.herokuapp.com/ I see what I expect. If I look a this one: https://myapp.herokuapp.com/xxyyyzzWhatever I also see what I expect. That is:

Cannot GET /xxyyyzzWhatever

Instead of displaying: Cannot GET /xxyyyzzWhatever I want to do other things. At this point I have referred to these documents: http://expressjs.com/en/guide/error-handling.html and http://thecodebarbarian.com/80-20-guide-to-express-error-handling; and I can get quite a bit of control on what is displayed.

I have implemented this kind of code:

app.get('*', function(req, res, next) {
  setImmediate(() => { next(new Error('woops')); });
});

app.use(function(error, req, res, next) {
  const xPt = req.path.substring(1,req.path.length);
  res.json({ message: error.message reachPoint: xPt});
});

But what I really want is to have something like:

if (xPt.substring(0,1) == "A") {display("You are lucky");}
else if (xPt.substring(0,1) == "Z") {display("You are very unlucky");}
else if ((xPt.substring(0,1) >= "B")&&(xPt.substring(0,1) <= "R")) 
  {goto("https://stackoverflow.com/")}
else {goto("http://www.google.com/")}

Any tip on the way to go?

Michel
  • 10,303
  • 17
  • 82
  • 179
  • [Related](https://stackoverflow.com/questions/6528876/how-to-redirect-404-errors-to-a-page-in-expressjs). – user202729 Mar 29 '18 at 04:46
  • 1
    Do you use ExpressJS framework or plain NodeJS server? – Alex Mar 29 '18 at 04:48
  • [Error handling middleware with Express](http://expressjs.com/en/guide/error-handling.html) – jfriend00 Mar 29 '18 at 04:51
  • 1
    A Node.js app that... uses... what? Express? Plain http responses? Custom httpd? Remember to [ask a good question](/help/how-to-ask), not just assume people know everything you know about your codebase. – Mike 'Pomax' Kamermans Mar 29 '18 at 05:04
  • Well, I have installed ejs, so I presume it uses Express. (My experience with Node.js is still far too limited to be aware of all the other possibilities I have). – Michel Mar 29 '18 at 05:17
  • I just updated my post. – Michel Mar 29 '18 at 07:38

1 Answers1

0

you can use following:

app.use(function (req, res, next) {
  res.status(404).send("Sorry can't find that!")
});

https://expressjs.com/en/starter/faq.html

Anshuman Jaiswal
  • 5,352
  • 1
  • 29
  • 46
  • Looking at some previous comments I made some progress. I updated the post to reflect that. – Michel Mar 29 '18 at 07:38