Angular 9 SSR 404 未找到带有状态代码的页面

2024-03-18

我正在使用 Angular 9 和 SSR,现在正在尝试获取 404 页面。它与客户端成功合作。但状态始终为 200 Ok。当我尝试使用 Angular ssr 时,它也显示 200 是状态代码。 我的 Angular 路由器已成功传递到 404 组件,但问题在于状态代码。请各位朋友帮帮我吧...

我的路由器详细信息 -

{
path: '404',
loadChildren: () => import('./not-found/not-found.module').then(m => m.NotFoundModule)
},
{
path: 'Home',
loadChildren: () => import('./all-india/all-india.module').then(m => m.AllIndiaModule)
},
{
path: '**',
loadChildren: () => import('./not-found/not-found.module').then(m => m.NotFoundModule)
}

我的未找到组件.HTML

<h1>404 Not Found</h1>

我的未找到 Component.ts 文件

import { Component, OnInit, Optional, Inject,Injector, PLATFORM_ID } from '@angular/core';
import { RESPONSE } from '@nguniversal/express-engine/tokens';
import { isPlatformServer } from '@angular/common';
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 response: Response,@Inject(Injector) private injector: Injector,
@Inject(PLATFORM_ID) private platformId: Object) { }

ngOnInit() {
 if(isPlatformServer(this.platformId))//Only executes server side
     {
         const response = this.injector.get(RESPONSE) as Response;
         response.status(404);
     }
}
}

我的 Server.TS 文件

import 'zone.js/dist/zone-node';

import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import {REQUEST, RESPONSE} from '@nguniversal/express-engine/tokens';
import { join } from 'path';

import { AppServerModule } from './src/main.server';
import { existsSync } from 'fs';

export function app() {
  const compression = require('compression');
  const server = express();
  server.use(compression());
  const distFolder = join(process.cwd(), 'dist/angular-httpclient-example/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';

  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
  }));

  server.set('view engine', 'html');
  server.set('views', distFolder);

server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

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

  return server;
}

function run() {
  const port = process.env.PORT || 4000;
  // Start up the Node server
  const server = app();
  server.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  run();
}

export * from './src/main.server';

我尝试了很多方法。状态代码没有任何作用。


创建服务器端响应服务

@Injectable({
  providedIn: 'root'
})
export class ServerSideResponseService {
  private response: Response

  constructor(@Optional() @Inject(RESPONSE) response: any) {
    this.response = response
  }

  setNotFound(message = 'not found'): this {
    if (this.response) {
      this.response.statusCode = 404
      this.response.statusMessage = message
    }
    return this
  }
}

并在未找到组件中使用它

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

  constructor(private ssr: ServerResponseService) {
    this.ssr.setNotFound();
  }
}

参考https://github.com/DSpace/dspace-angular/commit/015b439a39208da4515eb4d18e4d21640fce1df0 https://github.com/DSpace/dspace-angular/commit/015b439a39208da4515eb4d18e4d21640fce1df0

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 9 SSR 404 未找到带有状态代码的页面 的相关文章

随机推荐

  • 如何对 Django 数据库迁移进行单元测试?

    我们使用 django 迁移 django v1 7 更改了数据库 数据库中存在的数据不再有效 基本上我想通过在单元测试中构建预迁移数据库 添加一些数据 应用迁移来测试迁移 然后确认一切顺利 一个人如何 加载单元测试时阻止新的迁移 I fo
  • 没有 AVAsset 的纯色 AVMutableComposition

    这是我的最终目标 我想使用AVVideoCompositionCoreAnimationTool从 Core Animation 创建视频 我不会在此组合中使用现有的 AVAsset 我的问题是 我该如何使用AVMutableComposi
  • 猫鼬预保存和验证之间的区别?什么时候使用哪一个?

    目前我正在使用pre save 进行验证 UserSchema pre save true function next done var self this in case inside a callback var msg helper
  • Angular 4 材质是否像 bootstrap 一样响应式?

    我正在使用 Angular 4 开始一个新项目 需要创建响应灵敏且令人愉悦的用户界面 bootstrap 为您提供响应能力 但没有物质感 棱角分明的材质提供了良好的 UI 体验https material angular io https
  • 防止箭头键更改选定的单选按钮

    我有几个单选按钮 我想阻止按下向上 向下箭头键来更改选定的单选按钮 如果您选择其中一个单选按钮 然后按向上 向下箭头键 它将选择上一个或下一个单选按钮 相反 我希望选择保持不变 为此我可以使用event preventDefault 在某些
  • Jgrid 生成 XML 时出现问题

    我正在使用 Jgrid 我像我们大多数人一样使用 Xml 将数据注入到网格中 我想要批量更新数据库 我的要求是 当我单击 保存更改 时 它会生成当前 更新的 网格数据的 Xml 那么 我如何生成Jgrid数据的Xml 请帮忙 这是代码
  • C++ 模板:返回 list::iterator

    我怎样才能使下面的代码工作 在编译过程中 我收到一条错误消息 告诉我searchForResource函数没有返回类型 template
  • 为什么我的 UILabel 不显示 NSInteger

    我有一个 ViewController 和 GameController 类 它是 NSObject 的子类 视图控制器有一个链接到它的按钮 并触发一个初始化 GameController 类的 IBAction 在 GameControl
  • 剪切背景以露出下面的图层

    有没有办法剪切 div 背景以暴露下面的图层 就像这样 to this 欢迎任何前沿的 CSS 规则 UPDATE 好的 我做了一个示例代码 http jsfiddle net coma 9ae7g 1 http jsfiddle net
  • 创建新文件时,vscode 让我选择一个编辑器

    When creating a new file vscode let me select an editor It hasn t do so and I don t want to choose one because I only us
  • 我应该如何处理 Perl 中不再使用的对象?

    我正在编写一个链接到外部资源的类 其中一种方法是破坏外部资源的删除方法 不应对该对象进行进一步的方法调用 我正在考虑设置一个标志 如果设置了标志 那么就会在所有方法中死亡 但是有没有更好 更简单的方法呢 也许涉及破坏 到目前为止 我真的很喜
  • Android Studio:“libpng 警告:iCCP:无法识别已编辑的已知 sRGB 配置文件”

    我花了几个小时试图解决这个问题 app mergeDebugResources AAPT err 927129865 C Users Will AndroidStudioProjects Splitter2 app build interm
  • 从两个绝对路径获取相对路径

    我有两个绝对文件系统路径 A 和 B 并且我想生成第三个文件系统路径来表示 A 相对于 B 使用案例 管理播放列表的媒体播放器 用户将文件添加到播放列表 新文件路径已添加到播放列表相对于播放列表路径 将来 整个音乐目录 包括播放列表 都会转
  • ANGULAR 2 - 组件共享数据服务

    这真的让我很头疼 我有一个不错的小应用程序 使用 Firebase 和 Angular 2 设置社交登录 一切都应该是实时的 基本上 当用户通过 Facebook 登录时 我希望将他们的个人信息传递到服务并存储为 Observable 并立
  • 如何在Python中的一个图形上绘制多个kdeplot

    我有以下数据 name val G Kittle 4 0 G Kittle 10 0 D Hopkins 3 0 L Fitzgerald 6 0 C Kupp 18 0 R Woods 21 0 N Harry 7 0 S Michel
  • Angular:创建 Angular 项目时出现新错误

    我使用时遇到此错误ng 新项目名称 发现无效的配置文件 angular json 请在运行命令之前删除该文件 我收到此错误 我不知道如何获得解决方案 我卸载了 angular cli 并再次安装 npm clean 缓存也不起作用 我不知道
  • 持续监听TCP端口

    我编写了一个能够通过 TCP 协议从端口接收数据的代码 我每 15 分钟从 ESP8266 接收一次数据 然后 ESP 进入深度睡眠模式 如何改变它才能使其持续工作 我想在 while 循环中创建一个新连接 但它不起作用 My code i
  • 如何在调用任何 url 时提供 ntlm 身份验证?

    我有一个使用 ntlm Windows 集成身份验证 进行身份验证的托管 URL 我在 windows 上使用 java 1 8 URL url new URL someUrl HttpURLConnection con HttpURLCo
  • 如果小程序在浏览器的 JRE 中运行,为什么机器上还需要 JRE?

    Applet 在浏览器的 JRE 中运行 这是否意味着您不必在计算机上安装 JRE 即可运行小程序 浏览器的 JVM is您计算机上安装的 JRE 浏览器通常不会附带自己的浏览器 它们只是使用您系统上已安装的任何浏览器 也许您混淆了 Jav
  • Angular 9 SSR 404 未找到带有状态代码的页面

    我正在使用 Angular 9 和 SSR 现在正在尝试获取 404 页面 它与客户端成功合作 但状态始终为 200 Ok 当我尝试使用 Angular ssr 时 它也显示 200 是状态代码 我的 Angular 路由器已成功传递到 4