【问题标题】:Prevent Angular 6 router from overriding routes defined in Express Server防止 Angular 6 路由器覆盖 Express Server 中定义的路由
【发布时间】:2018-11-30 10:47:00
【问题描述】:

如何防止 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 应用程序。

【问题讨论】:

    标签: node.js angular express webpack angular2-routing


    【解决方案1】:

    如果您使用的是 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'));
    });
    

    【讨论】:

    • 感谢您的回复!我也这么认为,因此我将“app.use(settings.httpAdminRoot,RED.httpAdmin)”部分放在角度路由处理部分之前。但也许 app.use 由于某种原因不会在这里工作。我会试一试,然后接受你的回答;)
    • 抱歉回复晚了。不幸的是,没有!你的回答是有道理的,可能会帮助别人,所以如果没有人有任何想法,我会接受它来帮助别人
    • 顺便说一句,如果您尝试在角度路由本身中路由到some-non-angular-path,那么它将无法正常工作。您必须通过提供完整路径来重定向,例如点击链接/按钮时说window.location.href='http://localhost:3000/some-non-angular-path'。这样,它将到达服务器端的 app.js,并且将处理相应的路由而不是 Angular。这在我尝试时奏效了。
    猜你喜欢
    • 1970-01-01
    • 2018-04-22
    • 2017-05-16
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 2016-04-11
    相关资源
    最近更新 更多