如果发现任何无效的URL,则角4 通用重定向到404页



我正在使用Angular 4 Universal用于我的应用程序,并使用以下代码重定向到404页面,如果找到了一些未知URL。

  {
path: '',
component: FullLayoutComponent,
data: {
  title: 'Home'
},
children: [
  {
    path: '',
    loadChildren: 'app/core/components/static/static.module#StaticModule'
  },
  {
    path: 'move',
    loadChildren: 'app/core/components/move/move.module#MoveModule'
  },
  {
    path: 'account',
    loadChildren: 'app/core/components/account/account.module#AccountModule'
  },
  { path: "**",redirectTo:"404"}
]

}

它将其重定向到Localhost:4200/404对于任何未知的URL,但如果我转到URL Localhost:4200,它也将我重定向到404。

任何线索肯定会有很多帮助。

谢谢

由于答案中最重要的部分缺少:您不仅应该重定向,还应设置正确的状态代码。为了这样做,您需要角度代码中的请求对象。然后,您可以访问通常附加到请求的响应对象 - 至少在Express。

export class NotFoundComponent implements OnInit {
  constructor(@Inject(PLATFORM_ID) private platformId: Object,
              @Optional() @Inject(RESPONSE) private response: Response) {
  }

  ngOnInit() {
    if (!isPlatformBrowser(this.platformId)) {
      this.response.status(404);
    }
  }
}

如果您使用的是Express和Ng Universal Express Engine,则可以将请求和响应传递给依赖项注入:

app.engine('html', (_, options, callback) => {
  renderModuleFactory(AppServerModuleNgFactory, {
    // Our index.html
    document: template,
    url: options.req.url,
    extraProviders: [
      // make req and response accessible when angular app runs on server
      <ValueProvider>{
        provide: REQUEST,
        useValue: options.req
      },
      <ValueProvider>{
        provide: RESPONSE,
        useValue: options.req.res,
      },
    ]
  }).then(html => {
    callback(null, html);
  });
})

由于我本人偶然发现了这个问题,所以我在博客文章中记录了程序。如果您需要更多的指导,请查看:

https://blog.thecodecampus.de/angular-universal-handle-404-set-status-codes/

将您的代码更改为如下 - :

  {
path: '',
component: FullLayoutComponent,
data: {
 title: 'Home'
},
children: [
  {
   path: '',
   loadChildren:'app/core/components/static/static.module#StaticModule'
},
{
 path: 'move',
 loadChildren: 'app/core/components/move/move.module#MoveModule'
},
{
 path: 'account',
 loadChildren: 'app/core/components/account/account.module#AccountModule'
}
 ]
},
{ path: "**",redirectTo:"404"}

最新更新