【问题标题】:Angular routing takes to home page on manual refresh or directly typing url角度路由在手动刷新或直接输入 url 时进入主页
【发布时间】:2019-07-04 10:11:00
【问题描述】:

我的 Angular 应用程序由 node.js 服务器提供服务。在手动刷新或直接输入 url /xyz 或 /abc 时,如下例所示。我看到它被定向到主页。

例如:我点击导航按钮(xyz 和 abc),它会将我带到 https://mywebsite/xyzhttps://mywebsite/abc。我只看到 /xyz 或 /abc 附加到 https://mywebsite

我在生产中有角度,我把它作为静态文件。我将展示一些代码 sn-p。 请我根据 JWT 对用户进行身份验证,它存储在 localStorage 中

应用路由

..I have imported those components here..
const appRoutes: Routes = [
  { path: 'home', component: HomeComponent , canActivate: [AuthGuard]},
  { path: '', component: HomeComponent,canActivate: [AuthGuard],
  //{ path: '', component: SigninComponent,
    children: [ 
      { path: '', component: xyz },
      { path: 'xyz', component: xyz },
      { path: 'abc', component: abc },
    ]}
];
@NgModule({
  imports: [
    RouterModule.forRoot(
      appRoutes

    )
  ],
  exports: [RouterModule],
  providers: [],
})
export class RoutingModule { }

app.js

app.use(express.static(path.join(__dirname, '/client')));

app.get('/',function(req,res){  
  res.sendFile(path.join(__dirname, 'client/index.html'));
}); 
    let index = path.join(__dirname, '../../client/index.html');
    res.sendFile(index);

我希望在重定向到 index.html 时将我带到应用程序路由。因此,我在https://mywebsite/abc 中进行手动刷新,我将留在https://mywebsite/abc 本身而不是主页。

index.html

<!doctype html>
<html lang="en">
    <head>
    <meta charset="utf-8">
    <title> Portal</title>
    <base href="/">
    <app-root>

        </app-root>
    </body>
</html>



【问题讨论】:

  • 您的 home 组件有 [AuthGuard],尝试移除 AuthGurad 并检查。
  • 我删除了 AuthGuard 并检查过,同样的问题。 AuthGuard 在本地存储中持久保存数据时返回 true

标签: javascript node.js angular angular-routing


【解决方案1】:

如果我理解正确,您当前所在的页面会在刷新时自动重定向。

要解决此问题,您需要在路由器中启用哈希路由,如下所示:

imports: [
    RouterModule.forRoot(appRoutes, {useHash: true})
  ],

这将使 Angular 在刷新时不会重定向到基础 url

【讨论】:

    猜你喜欢
    • 2019-05-20
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多