刷新页面时如何修复Cannot GET/in Angular? [英] How to fix Cannot GET / in Angular when refreshing the page?
问题描述
我是 Angular 世界的新手.我按照 Angular.io 指南来路由我的应用程序及其许多页面.我遇到的问题是当我点击浏览器中的刷新按钮时.我是无法获取/仪表板"我一直在研究这个问题,我确实有 href="/" 放置.
I'm new in the Angular world. I followed Angular.io guide for routing my application and its many pages. The issue I have is when I hit the refresh button in the browser. I a "Cannot GET /dashboard" I have been researching about this issue and I do have the href="/" in placed.
这是我的路由文件
const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: '', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
{ path: '**', redirectTo: '', pathMatch: 'full' }
];
@NgModule({
imports: [
RouterModule.forRoot(
routes,
{
enableTracing: false
}
)],
exports: [RouterModule]
})
export class AppRoutingModule { }
如前所述,我可以访问 url,但是当我刷新页面时,我得到无法获取/dashboard" 有什么特别的我需要做来解决这个问题吗?刷新页面时如何修复Cannot GET/in Angular?
As mentioned before, I can get to the url but when I refresh the page I get the "Cannot GET /dashboard" Is there anything special I need to do to fix this issue? How to fix Cannot GET / in Angular when refreshing the page?
推荐答案
您的服务器需要设置为无论 URL 是什么都返回基本 HTML 页面,以便客户端路由器可以看到 /dashboard代码> 并从那里拿走它.否则,当您直接转到
/dashboard
时,您的服务器会认为您要求它提供仪表板页面.
Your server needs to be set up to return the base HTML page no matter the URL, so the client side router can then see /dashboard
and take it from there. Otherwise, when you go directly to /dashboard
your server will think you're asking it for a dashboard page.
您可以在 IIS 中使用 URL 重写来完成此操作.这是 https://blog.angularindepth.com/的示例deploy-an-angular-application-to-iis-60a0897742e7:
You could accomplish this in IIS using URL rewrites. Here's an example from https://blog.angularindepth.com/deploy-an-angular-application-to-iis-60a0897742e7:
<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="./index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
另一种选择是基于哈希的 URL,可以这样完成:
Another option is hash-based URLs, which can be accomplished like this:
RouterModule.forRoot(routes, { useHash: true })
这是有效的,因为服务器看不到 URL 的哈希部分.请参阅 https://angular.io/guide/router 了解详情.
This works because the server doesn't see the hash portion of the URL. See https://angular.io/guide/router for details.
这篇关于刷新页面时如何修复Cannot GET/in Angular?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!