使用 Express 服务 Angular 个应用及其 API
Serve Angular App and its API using Express
我设置了一个 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 应用程序就会出现,但是如果我导航到 within[=27] 中的任何一条路线=] 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 模板中有 <base href="/myapp/"/>
来支持这一点。所以我想知道是否唯一的方法 "correctly" 是使用 Express 应用程序的反向代理并让它 仅 服务于 API 路由,然后在 Apache 中使用某种 mod_rewrite 配置直接从 Apache 托管 Angular 应用程序。你怎么看?
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
上刷新而不是 root
,index.html
尚未加载。因此,浏览器不知道您从 Angular 定义的 Routes
。
我设置了一个 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 应用程序就会出现,但是如果我导航到 within[=27] 中的任何一条路线=] 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 模板中有 <base href="/myapp/"/>
来支持这一点。所以我想知道是否唯一的方法 "correctly" 是使用 Express 应用程序的反向代理并让它 仅 服务于 API 路由,然后在 Apache 中使用某种 mod_rewrite 配置直接从 Apache 托管 Angular 应用程序。你怎么看?
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
上刷新而不是 root
,index.html
尚未加载。因此,浏览器不知道您从 Angular 定义的 Routes
。