How to return 404 using Iron Router
Asked Answered
P

3

9

When I hit a route that doesn't exist on my Meteor app that uses IR, I get a 200 response with an HTML that (when rendered on a browser) displays a js error on console saying that No route found for path: "/aRoute".

How can a make it return 404?

Psychotic answered 18/11, 2014 at 18:23 Comment(0)
D
7

There don't seem to be a correct (or even working?) way of handling real 404's right now. See this issue for example: https://github.com/EventedMind/iron-router/issues/1055

Even when you try ways which should work, you'll still end up with a 200 status code. Like this code below which should work:

this.route( 'pageNotFound', {
  path: '/(.*)',
  where: 'server',
  action: function() {
    this.response.writeHead(404);
    this.response.end( html );
  }
});
Declension answered 18/11, 2014 at 19:36 Comment(1)
Thanks! We'll have to wait for that issue to be solved.Psychotic
G
7

I find this much easier way to show page not found. In router.js

Router.configure({
    layoutTemplate: "layout",
    loadingTemplate: "loading",
    notFoundTemplate: "notFound"
})

Here "notFound" could be any template where you want to show 404 error

Geoponics answered 18/11, 2014 at 18:47 Comment(2)
The problem is that I'm trying to return an error code for another app to consume. Also, isn't this code for the client router instead of the server one?Psychotic
no, this does not return a 404 status code, the code is still 200.Bircher
D
7

There don't seem to be a correct (or even working?) way of handling real 404's right now. See this issue for example: https://github.com/EventedMind/iron-router/issues/1055

Even when you try ways which should work, you'll still end up with a 200 status code. Like this code below which should work:

this.route( 'pageNotFound', {
  path: '/(.*)',
  where: 'server',
  action: function() {
    this.response.writeHead(404);
    this.response.end( html );
  }
});
Declension answered 18/11, 2014 at 19:36 Comment(1)
Thanks! We'll have to wait for that issue to be solved.Psychotic
B
0
this.route('template404', {
  path: '/*'
}

Use it at the end of your Router.map, cause this catches every value - if you use at the begining every path will be caught to this

Of course you can make it more complex, for example:

this.route('template404', {
      path: '/posts/*'
    }
Bumbling answered 18/11, 2014 at 18:28 Comment(2)
I get the same errot with the first solution.Psychotic
It doesn't work either. Do you have it working? on which version of Meteor/IR?Psychotic

© 2022 - 2024 — McMap. All rights reserved.