Angular Universal生成404(和其他HTTP代码)标头

时间:2017-09-14 12:52:27

标签: angular seo angular-universal

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

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

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

2 个答案:

答案 0 :(得分:2)

好的,我终于成功了。

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

答案 1 :(得分:0)

我关注了文档: 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);
    }
  }

}