防止 Angular 6 路由器覆盖 Express Server 中定义的路由

Prevent Angular 6 router from overriding routes defined in Express Server

如何防止 Angular 路由干扰来自 Express 节点服务器的路由?

我正在我的 Express 服务器中设置一些路由(到 node-RED 中间件):

server.js

    // Serve the editor UI from /red
app.use(settings.httpAdminRoot,RED.httpAdmin);

// Serve the http nodes UI from /api
app.use(settings.httpNodeRoot,RED.httpNode);

// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));

// Send all other requests to the Angular app
app.get('*', (req, res) => {

  res.sendFile(path.join(__dirname, 'dist/index.js'));
});

但在我的路由器模块中,它们总是被覆盖(我们没有默认路径重定向)

routing.module.ts

const appRoutes: Routes = [
    {
        path: "example-page",
        loadChildren: "../modules/example/example.module#ExampleModule?sync=true"
    },
    // Last routing path specifies default path for application entry
/*    {
        path: "**",
        redirectTo: "/example-page",
        pathMatch: "full"
    },*/
];

我只提供这个小代码,因为我想问一下 如何防止 Angular 干扰 Express 服务器 中定义的路由以及什么是在 Express/ Node.js + Angular + AspNetCore + Webpack 应用程序中路由的最佳实践。

如果您使用 Angular,则让 Angular 处理所有页面。此代码会处理此问题,因此 angular 正在处理所有路由。

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.js'));
});

如果您希望 express 处理某些路由而不是 angular,请在处理 angular 路由之前处理该路由,如下所示:

app.get('/some-non-angular-path', (req, res) => {
   //code to handle this path. once it is handled here, angular won't be involved
   //non-angular-paths should come first in the order
});
app.get((req, res) => {
   res.sendFile(path.join(__dirname, 'dist/index.js'));
});