首页 > 解决方案 > 如何配置 express 以在生产中提供 Angular 应用程序?

问题描述

客户端路由机制存在一个常见问题:一旦部署,所谓的“深层链接”host/deep/deeper/deepest/link/1会吐出 404 Not Found rahter,然后传播到index.html特定组件并正确解析。

我该如何配置它?

我试过:

app.use(express.static(root)); // root folder of the project
app.use((req, res) => res.sendFile(path.join(__dirname, root,'index.html')));

...但它仅适用于基本网址;所有其他人都被拒绝。

标签: angularexpressproduction-environment

解决方案


app.use(express.static(root)); // root folder of the project

这意味着没有挂载路径的中间件功能。对路由器的每个请求都执行此代码

尝试使用看起来像这样

  app.use('/', express.static(path.join(__dirname, '../root')));

  app.get('/*', function(req, res) {
    res.sendFile(path.join(__dirname, '../root/index.html'));
  });

完整的示例在这里 https://github.com/mdshohlrana/mean-stack/blob/master/server/app.ts


推荐阅读