如何处理Ember.js中的"无路由匹配"并显示404页面?

ste*_*nos 47 ember.js

我该如何处理错误

Uncaught Error: No route matched the URL '...'
Run Code Online (Sandbox Code Playgroud)

并显示自定义404页面?


注意:这个问题之前曾被问到并在几个月前得到回答 - 但不再适用了.

lau*_*iad 55

App.Router.map(function() {
  //set up all of your known routes, and then...
  this.route("fourOhFour", { path: "*path"});
});
Run Code Online (Sandbox Code Playgroud)

..您已经定义了FourOhFourRoute,以显示您选择的"找不到路线"消息.您将能够访问fourOhFour路径中最初请求的路径作为路径参数.

编辑:为了清楚起见 - 这个答案是在其他人报告不再工作之后发生的.

编辑2:我已经更新了答案,以反映耶胡达卡茨的评论(如果我错了,请LMK).

  • `:`不应该是必需的,但是参数名是(所以你可以从你的路线获得,如果你想要的话).`*path`就是我用的. (9认同)
  • 如果你使用的是ember cli,你的模板文件应该是dasherized(即4-oh-four.hbs) (2认同)

pix*_*ler 12

这是一个例子:

我使用通配符路由定义路由器中的最后一条路由,请参阅:http://emberjs.com/guides/routing/defining-your-routes/#toc_wildcard-globbing-routes

我有一个/not-found路由,看到我的路由器中定义的最后路由/*path捕获任何文本字符串,请参阅:https://github.com/pixelhandler/blog/blob/master/client/app/router.js#L19

Router.map(function () {
  this.route('about');
  this.resource('posts', function () {
    this.resource('post', { path: ':post_slug' });
  });
  this.resource('admin', function () {
    this.route('create');
    this.route('edit', { path: ':edit_id' });
  });
  this.route('not-found', { path: '/*path' });
});
Run Code Online (Sandbox Code Playgroud)

该路由重定向/not-found,请参阅:https://github.com/pixelhandler/blog/blob/master/client/app/routes/not-found.js

import Ember from 'ember';
export default Ember.Route.extend({
  redirect: function () {
    var url = this.router.location.formatURL('/not-found');
    if (window.location.pathname !== url) {
      this.transitionTo('/not-found');
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

还具有钩的任何途径(例如model,beforeModel,afterModel),其导致被拒绝的承诺,可以使用error动作转换到404.

actions: {
  error: function (error) {
    Ember.Logger.error(error);
    this.transitionTo('/not-found');
  }
}
Run Code Online (Sandbox Code Playgroud)

哪个呈现not-found模板,请参阅:https://github.com/pixelhandler/blog/blob/master/client/app/templates/not-found.hbs

<h1>404 Not Found</h1>
<p>
  Perhaps you have a link that has changed, see {{#link-to 'posts'}}Archives{{/link-to}}.
</p>
Run Code Online (Sandbox Code Playgroud)

这是我的404页面:http://pixelhandler.com/not-found

  • 好方案!我发现使用replaceWith而不是transitionTo更合适,否则如果用户点击浏览器上的"后退"按钮,他们将始终被重定向回/未找到页面,因为他们试图返回到页面原来没找到. (2认同)

Jam*_*sen 6

您可以尝试在路由器末尾添加catch-all路由:

App.Router.map(function() {
  this.resource('post', ...);
  this.resource('user', ...);
  this.route('catchAll', { path: '/*' });
});

App.CatchAllRoute = ...
Run Code Online (Sandbox Code Playgroud)