Is there a way to catch all non-matched routes wit

2020-02-18 04:43发布

问题:

I want to have a 'catch all' route which runs when none of the other defined routes are matched. A type of 404 NotFound error handler.

I've tried adding this, which works but prevents other routes from matching:

this.route(/(.*)/, 'notFound', this.notFound);

Anyone solved this problem before?

回答1:

Answering here for completeness.

You can do this 2 ways. Define the regular expression using route(), as in the question. However, due to this bug you would need to define all your routes via the route() method, and in reverse order (catchall at top). This prevents you from using the routes hash, so (my) preferred method is:

routes: {
  'users/search': 'searchUsers',
  'users/:id': 'loadUser',

  '*notFound': 'notFound'
}

The key '*notFound' can actually be anything starting with *. You just require characters after the * to prevent a parsing error.



回答2:

There's another, arguably simpler/more elegant way to solve this. Backbone.History.start() returns either true or false based on whether it matched a route or not. So, if you just do:

if (!Backbone.history.start()) router.navigate('404', {trigger:true});

instead of the usual:

Backbone.History.start();

it will have the same effect as the other answers.



回答3:

This very tiny plugin gets its job done: https://github.com/STRML/backbone.routeNotFound

It's the most elegant and robust way of solving this issue I've found so far, however please keep in mind that by using it, you are messing with Backbone's internals.



回答4:

Without an example of your current routing code I would presume ensuring your catch all route is the last route should work for you



回答5:

Just add it as the last route in the list. That way it will only be matched as the fallback option.



回答6:

You can hack it in to backbone like this:

var _loadUrl = Backbone.history.loadUrl;
Backbone.history.loadUrl = function (fragment) {
    var result = _loadUrl.apply(Backbone.history, fragment);
    // the loadUrl returns false if no route was found.
    if(!result){
        // call 404 route on router if it exists.
        var handler = Backbone.history.handlers.filter( o => o.route.test("404") )
        if(handler.length) {
            Backbone.history.navigate("/404")

        }
    }
}

Then in your router you can do like this:

var Router = Backbone.Router.extend({
    routes: {
        "404": "pageNotFound"
    },

    pageNotFound: function () {
        alert("trigger pageNotFound route")
    }
});


回答7:

I think this should not pass JavaScript to solve, should be the language to solve, for example php. On the server side processing of words, as long as you have the condition you can response head with error number 404