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

时间:2014-05-16 22:52:24

标签: 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
    });
  }
});

当我使用此路径http://example.com/region/xgok3Etc5mfhtmD7j

时,此方法正常

xgok3Etc5mfhtmD7j是地区的_id。但是,当我访问http://example.com/region/whatever时,页面正常呈现,但没有数据。

如何为此引发404错误?

4 个答案:

答案 0 :(得分: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;
  }
});

答案 1 :(得分:5)

我想你可以尝试Plugins

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

Router.plugin('dataNotFound', {notFoundTemplate: 'notFound'});

它被描述为

  

如果路线的数据是假的,这个开箱即用的插件会自动呈现名为“notFound”的模板

答案 2 :(得分:0)

在router.js

Router.configure({
    layoutTemplate:'layout',
    notFoundTemplate: 'notFound'
});

以这种方式配置路由器以解决问题

和模板部分

<template name="notFound">
    <div class="container">

            <h1 class="colorWhite">Oopss..ss..ss..</h1>
            <p class="colorWhite">You are out of the world, let's go back</p>

    </div>
</template>

让它像这样..它应该有效,事实上,它对我有用..

答案 3 :(得分:-1)

我在Router.map上列出了所有路线:

router.js

Router.map(function() {

    ... // other routes

    this.route('404', {
       path: '/*',
       layoutTemplate: 'application', // this actually lives in Router.configure();
       template: 'pageNotFound',
       onBeforeAction: function(){
          console.log('not found');
       }
    });
});

templates.html

<template name="pageNotFound">
    <div>
        <h2>404 - page not found</h2>
    </div>
</template>

<template name="application">
    <div>
        <h1>My Application</h1>

        {{> yield}}

    </div>
</template>

如果其他路线都没有获取uri路径,则此pageNotFound模板会在{{> yeild}}模板的application部分中呈现。

相关问题