如何使用路径为 http://myapp/mycontextpath 的路由在 Cloud Foundry 上部署 Angular 应用程序?

How to deploy Angular application on Cloud Foundry using route with path like http://myapp/mycontextpath?

我正在尝试在 CloudFoundry 上部署我的 Angular (6) 应用程序。 我想将我的应用程序映射到像 http://myapp.domain.com/mycontextpath 这样的路线上,所以 WITH A PATH。 为此,我使用如下 yml 文件部署我的应用程序 (CF PUSH):

---
[...]
buildpack: https://github.com/cloudfoundry/staticfile-buildpack.git
applications:
- name: myangularapp
  routes:
    - route: myapp.domain.com/mycontextpath

事实上,我尝试了很多事情,比如使用或不使用 --base-href 参数来构建我的应用程序。

ng build --prod --stats-json --base-href /mycontextpath/

ng build --prod --stats-json

我的结果总是 404 未找到。 如果我在没有路径的路由上部署应用程序(并且没有 angular --base-href),一切都运行良好。 我还尝试添加 Staticfile 文件 pushstate: enabled 内容,但在这种情况下,我的 index.html 总是被返回。

感谢帮助

事实上,我通过将额外的 mycontextpath 根目录添加到我推送到 Cloud Foundry 的 dist.zip 文件来解决我的问题。

要使用 Angular 6,您可以更新 angular.json 文件:

{
  [...]
  "projects": {
    "myangularapp": {
      [...]
      "architect": {
        "build": {
          [...]
          "options": {
            "outputPath": "dist/mycontextpath",
  [...]

并压缩dist文件夹内容。

确实,您需要在最终工件中有一个 contextpath 文件夹,并且在构建时需要 base-href 选项。 但是如果你想要 pushstate,你需要一些额外的步骤(见下文)

所以,完整的答案是:

1) 添加 base-href 选项到构建命令:

ng build --prod --base-href /mycontextpath/

2) 添加一个额外的对应于 mycontextpath 的文件夹(几乎从 Angular 6 完成):

{
  [...]
  "projects": {
    "myangularapp": {
      [...]
      "architect": {
        "build": {
          [...]
          "options": {
            "outputPath": "dist/mycontextpath",
  [...]

3) 在清单文件中设置路由:

---
[...]
buildpack: https://github.com/cloudfoundry/staticfile-buildpack.git
applications:
- name: myangularapp
  routes:
    - route: myapp.domain.com/mycontextpath

4) 使用 :

设置您的 ./Staticfile
root: dist 
location_include: includes/*.conf

5) 在 ./nginx/conf/includes/push_state.conf 中创建您的自定义位置配置:

location /mycontextpath/ {

    if (!-e $request_filename) {
      rewrite ^(.*)$ /mycontextpath/ break;
    }

    index index.html index.htm Default.htm;

}

6) 推送 dist 文件夹而不是 mycontextpath(这是因为 location_include 属性 需要自定义根目录)。这是推送到 CF 的最终结构:

./Staticfile
./nginx/conf/includes/push_state.conf
./dist/mycontextpath/index.html
./dist/mycontextpath/main-es2015.543563456.js
...

7)关于静态资源,一定要使用相对于base-href的路径:

<img alt="unicorn" src="./assets/unicorn.png"/>