Braulio Soncco
Braulio Soncco

Reputation: 353

Meteor and Iron Router: raise 404 when id doesn't exist

I'm using Iron Router for my urls and I have this route:

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

This works fine when I use this path http://example.com/region/xgok3Etc5mfhtmD7j

Where xgok3Etc5mfhtmD7j is the _id of region. However, when I access to http://example.com/region/whatever, the page renders normally, but without data.

How can I raise a 404 error for this?

Upvotes: 7

Views: 3357

Answers (4)

Mahesh Babu
Mahesh Babu

Reputation: 145

In router.js

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

Configure your router this way to solve the issue

and Template Part

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

make it like this.. it should work, in fact, it works for me..

Upvotes: 0

I think you can try Plugins

According to this documentation there is already a built in plugin for this issue

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

And it is described as

This out-of-box plugin will automatically render the template named "notFound" if the route's data is falsey

Upvotes: 5

Joshua
Joshua

Reputation: 6665

I include a catch all route on my 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>

This pageNotFound template then gets rendered in the {{> yeild}} partial of the application template if none of the other routes pick up the uri path.

Upvotes: -1

landland
landland

Reputation: 2147

not a 404, but you can render a not found page by doing something like this.

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

Upvotes: 8

Related Questions