How to redirect from pages without trailing slashe

2019-07-15 20:38发布

I have sammy.js running in a knockout.js app. I'm currently trying to redirect routes that are missing the trailing slash (for example /#/stop/1/100032) I would like to redirect all such pages missing the trailing slash, to the page with the trailing slash.

To complicate things, I would also like to have an error page in the case that there is no such route.

function RoutesViewModel () {
    var self = this;

    self.router = Sammy(function () {
        this.get('/#/stop/:agency_id/:stop_id/', function () {
            app.page.state('bus');
            app.stop.setCurrentById(this.params['agency_id'], this.params['stop_id']);
            mixpanel.track('stop page load', {
                'route': '/#/stop/' + this.params['agency_id'] + '/' + this.params['stop_id'] + '/',
            });
        });
        this.get('/(.*[^\/])', function () {
            this.redirect('/',this.params['splat'],'/');
        });
    });

    self.router.error = function (message, error) {
        app.page.header("Unable to find your page");
        app.page.message("The page you've requested could not be found.<br /><a href=\"/\">Click here</a> to return to the main page.");
    }

    self.run = function () {
        self.router.run();
    }
}

Above is a selection of the routes I have so far. Unfortunately, when I go to the example url above, the page loads the error, instead of the correct /#/stop/1/100032/.

Any help would be greatly appreciated.

标签: sammy.js
2条回答
We Are One
2楼-- · 2019-07-15 21:00

I know this is an old question, but I encountered this issue as well.

According to http://sammyjs.org/docs/routes routes are regular expressions. So this worked for me:

this.get('#/foo/:id/?', function() {
查看更多
Emotional °昔
3楼-- · 2019-07-15 21:05

I had this same problem, and decided to fix it with a catch-all at the end of my Sammy set-up. My solution removes the trailing slash if there is one, but you could easily do the reverse, adding a slash on instead:

Sammy(function () {
    this.get('#', function () {
        // ...
    });
    this.notFound = function (method, path) {
        if (path[path.length - 1] === '/') {
            // remove trailing slash
            window.location = path.substring(0, path.length - 1);
        } else {
            // redirect to not found
        }
    }
});
查看更多
登录 后发表回答