我正在使用 Angular Universal 创建一个网站。它将具有服务器端呈现,以便使其可以被搜索引擎索引。
我已经对我的 404 回退路由进行了编码,它正确显示了它的组件,但它使用 HTTP 200 header 代码显示它。
如何强制使用特定的 header 代码?我用谷歌搜索了一些查询,但我发现的所有内容似乎都是关于读取 HTTP 调用的状态代码,而没有关于如何将它写入浏览器的内容。
最佳答案
我遵循了文档: https://github.com/angular/universal/tree/master/modules/express-engine
请注意,您在 server.ts 中引导应用程序两次,我们需要为每个请求提供响应。 我们还可以选择将响应注入(inject)到我们的应用程序组件中,因为如果平台是浏览器,则响应将为 NULL。
服务器.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);
}
}
}
关于Angular Universal 生成 404(和其他 HTTP 代码) header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46219720/