如何从不带斜杠的页面重定向到带斜杠的页面

如何从不带斜杠的页面重定向到带斜杠的页面

本文介绍了如何从不带斜杠的页面重定向到带斜杠的页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个sammy.js运行在敲门(snockout.js)应用程序中.我目前正在尝试将缺少斜杠的路由(例如/#/stop/1/100032)重定向到所有缺少斜杠的页面,以重定向到带有斜杠的页面.

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();
    }
}

以上是我到目前为止选择的路线.不幸的是,当我转到上面的示例URL时,页面会加载错误,而不是正确的/#/stop/1/100032/.

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/.

任何帮助将不胜感激.

推荐答案

我遇到了同样的问题,因此决定在我的Sammy设置结束时使用包罗万象的方法进行修复.我的解决方案会删除斜杠(如果有的话),但是您可以轻松地进行反斜杠,而在斜杠上添加一个斜杠:

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

这篇关于如何从不带斜杠的页面重定向到带斜杠的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:07