You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular 2+(Angular Universal)中返回404状态码

Angular Universal 下处理404页面返回200状态码的解决方案

1. 配置通配符路由指向404组件

在app-routing.module.ts中添加匹配所有未定义路由的通配符规则,指向你的404组件:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { NotFoundComponent } from './not-found/not-found.component';

const routes: Routes = [
  // 你的业务路由配置
  { path: '**', component: NotFoundComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

2. 在Server端设置404响应状态码

利用Angular Universal的服务器端渲染能力,在404组件中注入RESPONSE对象,当在服务器端渲染时设置响应状态码为404:

import { Component, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformServer } from '@angular/common';
import { RESPONSE } from '@nguniversal/express-engine/tokens';
import { Response } from 'express';

@Component({
  selector: 'app-not-found',
  templateUrl: './not-found.component.html'
})
export class NotFoundComponent {
  constructor(
    @Inject(PLATFORM_ID) private platformId: object,
    @Inject(RESPONSE) private response: Response
  ) {
    // 仅在服务器端执行状态码设置
    if (isPlatformServer(this.platformId)) {
      this.response.status(404);
    }
  }
}

同时确保server.ts中正确传递RESPONSE提供者:

import { ngExpressEngine } from '@nguniversal/express-engine';
import { APP_BASE_HREF } from '@angular/common';
import { RESPONSE } from '@nguniversal/express-engine/tokens';

// ... 其他代码

server.engine('html', ngExpressEngine({
  bootstrap: AppServerModule,
}));

server.set('view engine', 'html');
server.set('views', join(DIST_FOLDER, 'browser'));

server.get('*', (req, res) => {
  res.render('index', {
    req,
    providers: [
      { provide: APP_BASE_HREF, useValue: req.baseUrl },
      { provide: RESPONSE, useValue: res }
    ]
  });
});

3. 验证效果

部署应用后,通过以下方式验证:

  • 使用curl命令:curl -I https://your-domain.com/nonexistent-page,查看返回的状态码是否为404
  • 在浏览器开发者工具的「网络」面板中,查看不存在页面的响应状态码

这样配置后,谷歌爬虫访问不存在的页面时会收到正确的404状态码,不会将这类页面收录。

内容的提问来源于stack exchange,提问作者Surya R Praveen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 10:42:18