【问题标题】:Angular 2 Universal 404 Not Found redirectionAngular 2 Universal 404 Not Found 重定向
【发布时间】:2017-06-23 08:47:18
【问题描述】:

我正在实现一个路由保护(CanActivate 接口),我需要在某些情况下重定向到未找到的页面。这可以通过以下语句来实现:

if (isNode){
let res : Response = Zone.current.get('res');
res.status(404).redirect('/not-found');
}else{
this.router.navigate(['not-found']);
}

这可行,但会引发服务器端异常(错误:发送后无法设置标头),因为无论重定向如何,angular2-universal 仍会发送呈现的页面。

有什么办法可以正确解决这个问题吗?

提前致谢。

【问题讨论】:

  • 在调用重定向之前,是否有任何代码可以输出一些东西?
  • 您找到解决方案了吗?

标签: angular2-universal


【解决方案1】:

其实有一个绕过错误的解决方案。

server.ts 中的res.render 方法中添加回调函数并检查res.headersSent 布尔值。

server.get('*', (req, res) => {
  res.render('../public/index.html', {req, res},
    (error, html) => {
      if(error)
        // error handle
      if (!res.headersSent) {
        res.send(html);
      }
    });
});

显然,仅当 res.headersSent 为 false 时才发送 html。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-30
    • 2018-09-07
    • 2016-11-07
    • 2017-02-20
    • 2014-05-11
    • 2017-07-15
    • 2010-10-07
    • 1970-01-01
    相关资源
    最近更新 更多