Angular 17 SSR中如何修改Express响应状态码?
在Angular 17+ SSR中修改Express响应状态码
Angular 17 改用官方的 @angular/ssr 包实现SSR,替代了原有的 @nguniversal/express-engine,修改响应状态码的核心逻辑和之前一致,仅需调整令牌的导入路径:
实现步骤与代码示例
- 从
@angular/ssr导入RESPONSE令牌,配合Angular依赖注入获取Express的Response对象 - 注入时添加
@Optional()装饰器,避免客户端渲染时因无实例而报错 - 在服务端渲染阶段调用
status()方法设置目标状态码
组件代码示例:
import { Component, OnInit, Optional, Inject } from '@angular/core'; import { RESPONSE } from '@angular/ssr'; import { Response } from 'express'; @Component({ selector: 'app-not-found', templateUrl: './not-found.component.html', styleUrls: ['./not-found.component.css'] }) export class NotFoundComponent implements OnInit { constructor( @Optional() @Inject(RESPONSE) private readonly response: Response ) {} ngOnInit(): void { // 仅在服务端渲染时执行状态码设置 if (this.response) { this.response.status(404); } } }
关键注意事项
- 必须添加
@Optional():客户端渲染时RESPONSE不会提供实例,不加会导致客户端运行报错 - 状态码设置前需判断
response是否存在:避免客户端触发Cannot read properties of null错误 - 该方案完全适配Angular 17+官方SSR,可满足NotFound页面设置404状态码的SEO需求
内容的提问来源于stack exchange,提问作者Mojtaba Nejad Poor Esmaeili
相关产品推荐
相关产品推荐

