【问题标题】:Serve Angular App and its API using Express使用 Express 服务 Angular App 及其 API
【发布时间】:2018-02-07 13:36:45
【问题描述】:

我有一个 Express 应用程序设置有这个路由配置:

app.use(express.static(path.join(__dirname, '../angular-app/dist')));
app.use('/', 
  express.Router().get('/', function(req, res, next) {
    res.redirect('index.html');
  })
);
app.use('/v1', v1); // these are my API routes

如果我启动这个 express 应用程序并(在浏览器中)导航到它的根目录,Angular 应用程序就会出现,但是如果我导航到 Angular 应用程序 的任何路线,例如/mycomponent/ 我从 Express 获得 404 路由渲染。

我想要发生的是,任何不以 /v1 开头的路由都被委托给 Angular 应用程序,否则我的 API 将被提供。这不是考虑如何部署这对应用程序的一种合理方式吗?

为了复合这一点,我使用反向代理配置将其托管在 Apache 服务器上。

   <Location /myapp>
      ProxyPass http://127.0.0.1:3000
      ProxyPassReverse http://1127.0.0.1:3000
   </Location>

...当然,我的 Angular 应用在​​其 index.html 模板中有 &lt;base href="/myapp/"/&gt; 来支持这一点。所以我想知道“正确”执行此操作的唯一方法是使用 Express 应用程序的反向代理并让它为 API 路由提供服务,然后在 Apache 中使用某种 mod_rewrite 配置直接从 Apache 托管 Angular 应用程序。你怎么看?

【问题讨论】:

  • 试试app.get('*', function(req, res, next) { res.sendFile(path.join(__dirname, '../angular-app/dist/index.html')); });
  • @ChauTran 是的,这非常简单,谢谢!把它变成一个答案,我会接受它。我在上面的 `app.use('/v1;, v1) 行之后直接复制粘贴了您的建议。

标签: angular express mod-rewrite apache2 reverse-proxy


【解决方案1】:
app.get('*', function(req, res, next) {
    res.sendFile(path.join(__dirname, '../angular-app/dist/index.html'));
});

将上面的代码块放在你的routes中间件之前。

原因是 Angular 是一个 SPA,这意味着它必须加载 index.html 和所有相应的 *.js,在其中一个 *.js 中,有你的 RouterModule 和你定义的 Routes。此时,您可以通过输入domain/route 导航到另一条路线,或者刷新domain/route,这不是rootindex.html 尚未加载。因此,浏览器不知道来自 Angular 的 Routes 定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 2016-08-01
    • 2018-07-13
    • 2015-12-16
    • 2019-05-30
    • 2015-05-13
    相关资源
    最近更新 更多