Angular 6 SSR:真正的 404/未找到页面,带有 404 HTTP 状态代码

Ger*_*rms 1 server-side-rendering angular

我努力解决一个 404 页面,该页面返回给导航器/爬虫特定的 HTTP 状态代码:404。按照https://angular.io/guide/universal 中的SSR 指南,我的应用程序正确地使用了 SSR。

我在 app-routing.module.ts 中设置了“PageNotfound”路由:

{path: '*', component: NotFoundComponent}
Run Code Online (Sandbox Code Playgroud)

但显然它仍然返回 200 作为 http 返回状态。如何更改此特定路由的 http 返回码?

小智 8

对我来说,以下代码段有效(Angular 8.2.11)。无需更改默认 server.ts 文件。

import { Component, OnInit, Inject, PLATFORM_ID, Optional } from '@angular/core';
import { REQUEST } from '@nguniversal/express-engine/tokens';
import { isPlatformServer } from '@angular/common';
import { Request } from 'express';

@Component({
  selector: 'app-error-not-found',
  templateUrl: './error-not-found.component.html',
  styleUrls: ['./error-not-found.component.scss']
})
export class ErrorNotFoundComponent implements OnInit {

  constructor(
    @Inject(PLATFORM_ID) private platformId: any,
    @Optional() @Inject(REQUEST) private request: Request
  ) { }

  ngOnInit() {
    if (isPlatformServer(this.platformId)) {
      if (this.request.res) {
        this.request.res.status(404);
      }
    }
  }

}
Run Code Online (Sandbox Code Playgroud)

当然,我们需要我们的路线是这样的:

export const routes: Routes = [
  ...
  { path: '404', component: ErrorNotFoundComponent },
  { path: '**', redirectTo: '/404' }
];
Run Code Online (Sandbox Code Playgroud)