【问题标题】:Angular routing - redirect url to component角度路由 - 将 url 重定向到组件
【发布时间】:2018-05-12 21:30:41
【问题描述】:

在生产模式下重定向我的应用时遇到问题。当我有 url http://server.com/projectname/dashboard 时,服务器响应 IIS 错误页面 404。我必须使用 http://server.com/projectname 打开应用程序,然后单击链接,例如:

<a [routerLink]="'dashboard'">Dashboard</a>

在 html 中我有 &lt;base href="./"&gt;,这是我的路由器:

const appRoutes: Routes = [
    { path: '', redirectTo: 'dashboard', pathMatch: 'full', canActivate: [AuthGuard] },
    { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard]},
    { path: '400', component: ErrorComponent, canActivate: [AuthGuard] },
    { path: '401', component: ErrorComponent, canActivate: [AuthGuard] },
    { path: '404', component: ErrorComponent, canActivate: [AuthGuard], 
    { path: '**', redirectTo: '/404' }
]

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes)
    ]
})

在开发模式下,我有 url http://localhost:4200/dashboard,我应该重定向。开发中是 url localhost:4200/dashboard 而生产中是 server.com/appname/dashboard 会不会有问题?

【问题讨论】:

    标签: angular angular2-routing angular2-template angular5 angular4-router


    【解决方案1】:

    您需要更新应用程序的基本 href。如果您使用angular-cli,我不会推荐@Daniel 的答案,因为有更简单的方法。

    使用angular-cli,您可以使用:ng build --prod --bh /appname/,这将更新生产构建基础href。这是一种更好的方法,因为在环境之间切换时您不必在 index.html 中手动更新它。

    Set base href dynamically - Angular 2 / 4

    【讨论】:

      【解决方案2】:

      当您在生产环境中部署时,在您的 index.html 中添加这一行:

      <base href="/appname/">
      

      【讨论】:

        【解决方案3】:

        我找到了原因。我必须配置回退。 Here 是关于它的文章。

        我必须添加 web.config:

        <?xml version="1.0" encoding="utf-8"?>
        <configuration>
          <system.webServer>
           <rewrite>
            <rules>
              <rule name="Angular Routes" stopProcessing="true">
                <match url=".*" />
                <conditions logicalGrouping="MatchAll">
                  <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                  <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
                </conditions>
                <action type="Rewrite" url="./" />
              </rule>
            </rules>
          </rewrite>
          </system.webServer>
        </configuration>
        

        现在它可以正常工作了,我可以打开任意应用程序 url。

        【讨论】:

          猜你喜欢
          • 2020-09-18
          • 2020-04-02
          • 1970-01-01
          • 2021-08-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-10
          • 2018-02-11
          相关资源
          最近更新 更多