当启动 Spartacus 时,路由由 Router
逻辑处理。将评估四种不同类型的路由:
- 路由应由自定义路由路径处理;客户添加了硬编码路由,并且我们应该优先考虑这些路由。
- 路由是 PLP(产品列表页)或 PDP(产品详情页)。
- 路由是 CMS(内容管理系统)内容页面。
- 路由是未知的(404 页面未找到)。
当向 Spartacus 提供不正确的 URL 时,它很可能属于第三种情况。Spartacus 将使用 CMS API 获取给定 URL 的内容页面。如果 CMS 找不到匹配的内容页面,它将返回 404 错误。Spartacus 将处理此 404 错误,并在幕后将用户重定向到未找到的 CMS 页面。
看个具体的例子:
我们访问这个 url:
其实就是在 category 578 后面添上一个 n。
然后看到这个 404 not found 的页面:
Spartacus 试图去 CMS 查找 id 为 578n 的 CMS page,当然找不到了。然后就找 not-found CMS page,这次找到了:
如果这是第一次访问,它将进入 SSR 服务器,并且实际上会导致一些不必要的处理。这为攻击者打开了一扇门,并会增加 SSR 服务器上不必要的负载。
一种优化的方式是,在 SSR 服务器上,我们应该立即重定向到一个(静态的)404 页面。
github 上有人提出了一种解决方案:
实现瑞啊的 interceptor:
@Injectable() export class NotFoundInterceptor implements HttpInterceptor { constructor( @Inject(PLATFORM_ID) private platformId: object, @Inject('response') private response: any, ) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { if (isPlatformServer(this.platformId)) { if (request.url.includes('/cms/pages')) { return next.handle(request).pipe( tap({ next: event => { if (event instanceof HttpResponse && event.status === 404) { this.response.status(404); } }, error: err => { if (err.status === 404) { this.response.status(404); } } }) ) } } return next.handle(request); } }
在 App module 里注册这个 interceptor:
providers: [ ... { provide: HTTP_INTERCEPTORS, useClass: NotFoundInterceptor, multi: true } ]
server.ts 的代码:
server.get('*', (req, res) => { res.render(indexHtml, { req, providers: [ { provide: APP_BASE_HREF, useValue: req.baseUrl }, { provide: 'request', useValue: req }, { provide: 'response', useValue: res } ], }, (_error, html) => { if (res.get('X-Response-Status') === '404') { console.log(`[Node Express] 404 for url ${req.baseUrl}`); res.status(404).send(html); } else { // return rendered html for default res.send(html); } } ); });