【问题标题】:Ember render 404 with Invalid URL SlugsEmber 使用无效的 URL Slug 渲染 404
【发布时间】:2015-02-14 05:06:42
【问题描述】:

为了便于阅读,我在我的应用程序中使用了动态 URL。 url 结构为/[:organization_slug]/[:product_slug]。换句话说,organization 是product 的所有者。出于安全目的,当有人在 URL 中键入不存在的组织时,我想显示 404。同样,在 URL 中输入不存在的产品时显示 404。

我已经按照in this post 的描述实现了 Ember 404。然后,我连接到afterModel 以查看查询是否返回了记录,如果没有则尝试转换到fourOhFour 路由。这是我目前的相关代码:

router.js

Router.map(function() {
  this.route("fourOhFour", {path: "*path"});
  this.resource('organization', {path: ':organization_slug'}, function() {
    this.resource('product', {path: ':product_slug'});
  });
});

routes/organization.js

var OrganizationRoute = Ember.Route.extend({
  model: function(params) {
    return this.store.find('organization', {slug: params.organization_slug});
  },
  afterModel: function(organization, transition) {
    if(organization.get('length') === 0) {
      //If it's not a correct URL render the 404
      this.transitionTo("fourOhFour");
    }
  },

  serialize: function(model) {
    return {organization_slug: model.get('slug')};
  }
});

export default OrganizationRoute;

routes/product.js

var ProductRoute = Ember.Route.extend({
  model: function(params) {
    var self = this;
    // Verify that the product belongs to the organization in the URL
    return this.store.find('organization', {slug: Ember.organizationSlug}).then(function(organization) {
      var organizationID = organization.get('firstObject.id');
      return self.store.find('product', {slug: params.product_slug, organization: organizationID});
    });
  },
  afterModel: function(product) {
    if(product.get('length') === 0) {
      this.transitionTo("fourOhFour");
    }
  },
  serialize: function(model) {
    return {product_slug: model.get('slug')};
  }
});

export default ProductRoute;

问题是过渡没有触发。路线未激活,模板未呈现。我认为这与由于动态 URL 的性质而存在路由的事实有关。但是,我想维护 URL 路径但显示 404 模板,该模板无法正常工作。如果我将 404 路由的 path 更改为像 /404 这样的静态字符串,则转换有效。但是,如果可能,我想保留原始请求的 URL 路径。

这样,如果有人请求实际上不存在的路由(即/foo/bar/baz),它将看起来与路由有效但记录不存在的页面相同。谁能指出我正确的方向?

提前致谢!

【问题讨论】:

    标签: javascript ember.js ember-data url-routing slug


    【解决方案1】:

    我相信您的问题是,当您尝试过渡到“包罗万象”时,Ember.js 不知道那是什么。这很容易解决,因为transitionTo() 采用第二个参数来指定模型,在您的情况下是 URL。

    因此,对于一个不存在的产品,您的路线看起来像这样:

    App.BadRoute = Ember.Route.extend({
      model: function(){
        return "abcdproduct";
      },
      afterModel: function(badProduct){
        this.transitionTo('notFound', badProduct);
      }
    });
    

    查看基本工作示例here

    【讨论】:

    • 感谢卡尔曼的帮助!我需要的是第二个参数。我稍微修改了您的答案以适用于我的特定情况。
    猜你喜欢
    • 2018-01-10
    • 2017-08-31
    • 2014-12-18
    • 2019-08-06
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 2013-03-18
    相关资源
    最近更新 更多