Mar*_*ult 8 seo angular-universal angular
我正在使用 Angular Universal 创建一个网站。它将进行服务器端渲染,以便搜索引擎可以对其进行索引。
我已经编码了 404 后备路由,它正确显示了其组件,但它显示了 HTTP 200 标头代码。
如何强制使用特定的标头代码?我用谷歌搜索了一些查询,但我发现的所有内容似乎都是关于读取HTTP 调用的状态代码,而没有关于如何将其写入浏览器的内容。
我遵循了文档: https ://github.com/angular/universal/tree/master/modules/express-engine
请注意,您在 server.ts 中引导应用程序两次,我们需要为每个请求提供响应。此外,我们还可以选择将响应注入到我们的应用程序组件中,因为如果平台是浏览器,则响应将为 NULL。
服务器.ts
一些进口:
import {Response} from 'express';
import {RESPONSE} from '@nguniversal/express-engine/tokens';
Run Code Online (Sandbox Code Playgroud)
引擎:
// * 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),
]
}));
Run Code Online (Sandbox Code Playgroud)
请求处理程序:
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);
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
路由:
const routes: Routes = [
{path: '404', component: NotFoundComponent},
...
{path: '**', redirectTo: '/404'}
];
Run Code Online (Sandbox Code Playgroud)
成分:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
好吧,我终于成功了。
我重新开始,并使用Angular Universal Starter (CLI),其中描述了 Patrick Michalina 的脚本: https: //github.com/DSpace/dspace-angular/issues/91#issuecomment-318547118
| 归档时间: |
|
| 查看次数: |
7178 次 |
| 最近记录: |