这个答案来自 eneajaho 来自 reddit。
嗨,几个月前我遇到了您的用例,我“找到”了一个解决方案,并且还在 Angular 存储库中打开了一个问题,以便在文档中添加解决方案,但没有成功。无论如何,这是问题所在:https://github.com/angular/angular/issues/41187
解决方案:您应该编辑发生服务器端路由的server.ts 文件,并添加一组您不想在服务器端呈现的路由。示例:
const EXCLUDED_ROUTES: string[] = [
'/test',
'/auth(/)?*',
'/back(/)?*',
];
然后,您应该在文件中添加一个包含排除路由的 get,在服务器呈现应用程序之前。而且这个路由会直接返回 index.html 文件,所以不会渲染它,而是将它作为一个静态文件,就像客户端渲染一样。
server.get(EXCLUDED_ROUTES, (req, res) => {
res.sendFile(join(distFolder, 'index.html'));
});
整个代码:
/**
* EXCLUDED_ROUTES contains all the paths that we don't want to render on the server
* Examples:
* '/test'
* '/back(/)?*' // regex: string starts with /back, '/' is optional, '*' it can be anything
*/
const EXCLUDED_ROUTES: string[] = [
'/test',
'/auth(/)?*',
'/back(/)?*',
];
/**
* Is used to exclude the routes from rendering on the server. Ex. Auth Page, Admin Page
* To add or remove excluded routes modify the EXCLUDED_ROUTES array
*/
server.get(EXCLUDED_ROUTES, (req, res) => {
res.sendFile(join(distFolder, 'index.html'));
});