本文介绍了Angular 6 SSR:包含404 HTTP状态代码的真实404/未找到页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难解决一个404页面,该页面向导航者/爬网者返回特定的HTTP状态代码:404.遵循 https://angular.io/guide/universal 中的SSR指南,我的应用程序可以正确使用SSR.

I struggle to settle a 404 page that returns to navigators/crawlers a specific HTTP status code : 404.Following SSR guide in https://angular.io/guide/universal, my application is correctly served with SSR.

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

I set a 'PageNotfound' route in my app-routing.module.ts :

{path: '*', component: NotFoundComponent}

但是很明显它仍然返回200作为http返回状态.如何更改此特定路线的http返回代码?

But obviously it still returns 200 as http return statuses.How I can change http return code for this specific route ?

推荐答案

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

For me the following snippet worked (Angular 8.2.11). No need to change the default server.ts file.

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);
      }
    }
  }

}

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

And offcourse we need our routes to be something like this:

export const routes: Routes = [
  ...
  { path: '404', component: ErrorNotFoundComponent },
  { path: '**', redirectTo: '/404' }
];

这篇关于Angular 6 SSR:包含404 HTTP状态代码的真实404/未找到页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 00:43
查看更多