如何使 angular2 路由与 express 路由器一起工作?

How to make angular2 routing work with express router?

我试图在同一台服务器上使用 angular2 应用程序托管我的快速休息服务。 在阅读了各种相关的 post 之后,我发现各种解决方案都在本地服务器上运行 http://localhost:3000 但是当我在 Heroku 上托管我的应用程序时,我尝试访问我的快速路线开始于/api/... 一切正常。但无法访问 angular2 UI 页面,它开始在页面上显示未找到消息。

app.all('*', (req, res) => {
  console.log(`[TRACE] Server 404 request: ${req.originalUrl}`);
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

app.use(function(req, res, next) {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

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

app.get(/^\/([^a]|a[^p]|ap[^i]|api[^/]).*$/,(req,res) => {
    res.sendFile(path.join(__dirname, 'dist/index.html'));
});

当我在托管服务器上部署我的应用程序时,我发现 dist 目录没有部署在包含 Angular 在 运行 ng 构建之后创建的应用程序构建的服务器上--产品

首先,我手动将其上传到托管服务器,然后我的应用程序开始正常运行。然后我想到每次都是手动任务,所以我找到了解决这个问题的两个方法。

  1. 首先,从 .gitignore 文件中删除 /dist 条目,这意味着当我将应用程序推送到任何托管服务器时它不会忽略 dist 目录。
  2. 其次,我阅读了来自此 link https://docs.npmjs.com/misc/scripts 的 package.json 文档,并了解了安装前和安装后脚本并更新了我的 package.json 文件以包含以下脚本。

    "scripts": {
       "ng": "ng",
       "start": "node index.js",
       "build": "ng build",
       "test": "ng test",
       "lint": "ng lint",
       "e2e": "ng e2e",
       "postinstall": "ng build --prod"
    },
    

阅读这篇关于在 heroku 上部署的文章 https://paucls.wordpress.com/2016/11/25/deploy-angular-2-cli-app-to-heroku/