【问题标题】:How to redirect from pages without trailing slashes to pages with trailing slashes如何从不带斜杠的页面重定向到带斜杠的页面
【发布时间】:2012-10-13 22:25:05
【问题描述】:

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

为了使事情复杂化,我还希望在没有这样的路线的情况下有一个错误页面。

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/

任何帮助将不胜感激。

【问题讨论】:

  • 您找到解决方案了吗?

标签: sammy.js


【解决方案1】:

我知道这是一个老问题,但我也遇到了这个问题。

根据http://sammyjs.org/docs/routes,路由是正则表达式。所以这对我有用:

this.get('#/foo/:id/?', function() {

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,并决定在我的 Sammy 设置结束时用一个全面的方法来解决它。如果有斜杠,我的解决方案会删除斜杠,但您可以轻松地做相反的事情,改为添加斜杠:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      • 1970-01-01
      • 2015-06-29
      • 2016-04-06
      • 1970-01-01
      • 2014-12-22
      相关资源
      最近更新 更多