【问题标题】:Angular Universal generate 404 (and other HTTP codes) headerAngular Universal 生成 404(和其他 HTTP 代码)标头
【发布时间】:2019-05-07 11:51:31
【问题描述】:

我正在使用 Angular Universal 创建一个网站。它将具有服务器端呈现,以使其可被搜索引擎索引。

我已经编写了我的 404 后备路由,它正确地显示了它的组件,但它使用 HTTP 200 标头代码显示它。

如何强制使用特定的标头代码?我搜索了一些查询,但我发现的所有内容似乎都是关于读取 HTTP 调用的状态代码,而没有关于如何将其写入到浏览器。

【问题讨论】:

  • ...这是状态码。
  • 对不起,我应该强调“阅读”,这是我现在不关心的事情,因为我想向浏览器“写”一个响应代码。
  • 你不能给浏览器写响应,浏览器是在 HTTP 上工作的。

标签: angular seo angular-universal


【解决方案1】:

我遵循了文档: https://github.com/angular/universal/tree/master/modules/express-engine

注意,您在 server.ts 中引导应用程序两次,我们需要为每个请求提供响应。 我们还可以选择将响应注入到我们的应用组件中,因为如果平台是浏览器,则响应将为 NULL。

server.ts

一些进口:

import {Response} from 'express';
import {RESPONSE} from '@nguniversal/express-engine/tokens';

引擎:

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./dist/server/main');

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP),
  ]
}));

请求处理程序:

app.get('*', async (req, res) => {
  res.render('index.html', {req, res, providers: [
      {
        provide: RESPONSE,
        useValue: res,
      },
    ]}, (error, html) => {
    if (error) {
      console.log(`Error generating html for req ${req.url}`, error);
      return (req as any).next(error);
    }
    res.send(html);
    if (!error) {
      if (res.statusCode === 200) {
        //toCache(req.url, html);
      }
    }
  });
});

路由:

const routes: Routes = [
  {path: '404', component: NotFoundComponent},
...
  {path: '**', redirectTo: '/404'}

];

组件:

import { RESPONSE } from '@nguniversal/express-engine/tokens'
import { Component, OnInit, Inject, Optional } from '@angular/core'
import { Response } from 'express'

@Component({
  selector: 'app-not-found',
  templateUrl: './not-found.component.html',
  styleUrls: ['./not-found.component.scss']
})
export class NotFoundComponent implements OnInit {
  private response: Response;
  constructor(@Optional() @Inject(RESPONSE) response: any) {
    this.response = response;
  }

  ngOnInit() {
    console.log('here with response', this.response);
    if (this.response) {
      // response will only be if we have express
      // this.response.statusCode = 404;
      this.response.status(404);
    }
  }

}

【讨论】:

【解决方案2】:

好的,我终于成功了。

我重新开始,使用 Angular Universal Starter (CLI),Patrick Michalina 的脚本在这里描述:https://github.com/DSpace/dspace-angular/issues/91#issuecomment-318547118

【讨论】:

猜你喜欢
  • 2018-11-28
  • 2013-02-18
  • 2018-03-07
  • 2021-06-03
  • 2012-04-01
  • 2010-09-05
  • 2017-07-31
  • 1970-01-01
  • 2011-06-25
相关资源
最近更新 更多