流星和铁路由器:当id不存在时提高404

Bra*_*cco 7 meteor iron-router

我正在使用Iron Router作为我的网址,我有这条路线:

this.route('regionEdit', {
  path: '/region/:_id',
  waitOn: function() {
    return Meteor.subscribe('region', this.params._id);
  },
  data: function() {
    return Regions.findOne({
      _id: this.params._id
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

当我使用这条路径时,这很好用 http://example.com/region/xgok3Etc5mfhtmD7j

哪里xgok3Etc5mfhtmD7j_id区域的.但是,当我访问时http://example.com/region/whatever,页面正常呈现,但没有数据.

如何为此引发404错误?

lan*_*and 8

不是404,但你可以通过做这样的事情来渲染一个未找到的页面.

this.route('regionEdit', {
  path: '/region/:_id',
  waitOn: function() {
    return Meteor.subscribe('region', this.params._id);
  },
  data: function() {
    var region = Regions.findOne({
      _id: this.params._id
    });
    if(!region)
      this.render("notFound");
    else
      return region;
  }
});
Run Code Online (Sandbox Code Playgroud)


Süh*_*kçu 5

我想你可以尝试插件

根据此文档,已存在针对此问题的内置插件

Router.plugin('dataNotFound', {notFoundTemplate: 'notFound'});
Run Code Online (Sandbox Code Playgroud)

它被描述为

如果路由的数据是假的,这个开箱即用的插件将自动呈现名为"notFound"的模板

  • `Router.configure({notFoundTemplate:'404'});`模板只有在找不到相应的Route时才会被渲染.由于OP使用params,因此将找到路径,因此将呈现,但没有数据. (2认同)