当启动 Spartacus 时,路由由 Router 逻辑解决。将评估四种不同类型的路由:

  1. 路由应由自定义路由门路解决;客户增加了硬编码路由,并且咱们应该优先思考这些路由。
  2. 路由是 PLP(产品列表页)或 PDP(产品详情页)。
  3. 路由是 CMS(内容管理系统)内容页面。
  4. 路由是未知的(404 页面未找到)。

当向 Spartacus 提供不正确的 URL 时,它很可能属于第三种状况。Spartacus 将应用 CMS API 获取给定 URL 的内容页面。如果 CMS 找不到匹配的内容页面,它将返回 404 谬误。Spartacus 将解决此 404 谬误,并在幕后将用户重定向到未找到的 CMS 页面。

看个具体的例子:

咱们拜访这个 url:

https://spartacus-demo.eastus.cloudapp.azure.com/electronics-...

其实就是在 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);        }      }    );  });