【问题标题】:404 page when refreshing Angular SPA on Digital Ocean App Platform在 Digital Ocean 应用平台上刷新 Angular SPA 时出现 404 页面
【发布时间】:2021-01-26 09:57:12
【问题描述】:

我一直在作为静态站点在新的 Digital Ocean 应用平台上测试 Angular 单页应用。

当我访问根 URL 并通过单击链接导航到不同页面时,Angular 应用程序加载正常。但是,当我在任何页面上刷新浏览器时,都会收到 404 错误。

数字海洋应用平台是否需要 nginx.conf 文件?我是否错过了需要在环境中启用 pushstate 的步骤?

【问题讨论】:

  • 你是在任何页面刷新或只是根页面刷新时得到 404 吗?
  • 我在刷新任何页面时都会收到 404。
  • 你是在 nginx 后面部署你的应用吗?如果是这样你需要配置 nginx 使其在 404 错误发生时正常工作。

标签: angular single-page-application digital-ocean static-site


【解决方案1】:

编辑:

您现在可以正式使用catchall_document 属性,而不是本说明中的error_document


我认为应用平台中的官方 SPA 目前是不可能的。更多信息在这里https://www.digitalocean.com/community/questions/digital-ocean-apps-spa-application

但现在有一个解决方法。

创建app.yaml 文件

name: APP_NAME
region: fra
static_sites:
- build_command: |-
    git init
    git clean  -d  -f .
    git remote add origin https://github.com/REPOSITORY
    git fetch origin $BRANCH_NAME
    git checkout $COMMIT_SHA
    npm install
    npm install -g @angular/cli
    ng build --prod
  environment_slug: node-js
  github:
    branch: master
    deploy_on_push: true
    repo: REPOSITORY
  name: APP_NAME
  error_document: index.html
  routes:
  - path: /

在这个文件中,我们将error_document 设置为index.html(我们的索引文件)。现在每个页面都被重定向到索引文件。

然后您必须运行 doctl 命令以使用 app.yaml 文件创建新应用程序。您必须使用此命令才能应用此配置文件。

doctl apps create --spec app.yaml

然后转到您的应用平台仪表板,您可以看到您的 SPA 应用程序

如何设置doctlhttps://www.digitalocean.com/docs/apis-clis/doctl/how-to/install/

如何查看我当前的.yaml 设置?在应用仪表板中点击 settings 选项卡并在 App spec 行中点击 view

就是这样

【讨论】:

  • 我刚刚在 DigitalOcean 上与人们交谈过,他们最近为静态站点添加了一个新选项:catchall_document。所以我们可以把“error_document: index.html”改成“catchall_document: index.html”。我在这里测试过,效果很好! =]
【解决方案2】:

更新(2020 年 11 月 24 日)控制面板现在支持“自定义页面”部分下组件设置中的 Catchall 文档选项。

https://www.digitalocean.com/community/questions/angular-routes-not-working-on-static-app

【讨论】:

    【解决方案3】:

    另一种解决方法是在角度路由之前使用“#”,例如:“myapp.com/#/someroute”(https://angular.io/guide/router)。

    在 app-routing.module.ts 中,在 RouterModule.forRoot 上将参数“useHash”设置为 true:

    @NgModule({
      imports: [
        RouterModule.forRoot(routes, {
          useHash: true,
        }),
      ],
      exports: [RouterModule],
    })
    

    我在这里遇到了同样的问题,而且效果很好。 在 DigitalOcean 解决此问题之前,我将使用这种方式。

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2017-12-17
      • 2021-06-05
      • 2021-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      相关资源
      最近更新 更多