jcubic / wayne

Service Worker Routing library for in browser HTTP requests
https://jcubic.github.io/wayne
MIT License
556 stars 29 forks source link

bug: "not found" handler intercepts already matched routes #36

Closed 7flash closed 4 months ago

7flash commented 4 months ago

I have a handler defined for my index page route as below:

app.get('/', function(req, res) {
  res.html(`<h1>Index Page</h1>`);
});

Then I want to add handler to show "not found" page for all other routes

app.get('*', function(req, res) {
  const accept = req.headers.get('Accept');
  if (accept.match(/text\/html/)) {
    res.html(render(`<h1>Page not found</h1>`));
  } else {
    res.fetch(req);
  }
});

Unfortunately when added this wildcard handler following after index route, then index route is not working anymore as expected and instead it shows "not found" message for defined index route as well.

jcubic commented 4 months ago

I need to think what to do. Wildcard grab everything, I'm not sure if this is a bug. I need to see if I can make it work as expected.

7flash commented 4 months ago

What can be a workaround to implement "not found" page in meantime?

jcubic commented 4 months ago

You will need to do your own routing with a single wildcard, but this will be almost the same as not using a library at all.

The routing library is not exposed, but it's based on route.js.

jcubic commented 4 months ago

It looks like this is how you add 404 page to express.js, so this is something that should be implemented.

jcubic commented 4 months ago

So the workaround now is to use wildcard as first route:

app.get('*', function(req, res) {
  const accept = req.headers.get('Accept');
  if (accept.match(/text\/html/)) {
    res.html(render(`<h1>Page not found</h1>`));
  } else {
    res.fetch(req);
  }
});

app.get('/', function(req, res) {
  res.html(`<h1>Index Page</h1>`);
});
jcubic commented 4 months ago

It should work now as expected, the way route works, is search from the end and first found was used. Now if there are more than 1 routes it picks first non wildcard.

jcubic commented 4 months ago

I'm releasing next version to NPM.