javascript - Angular 路由通过手动刷新或直接输入 url 进入主页

标签 javascript node.js angular angular-routing

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

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

我在生产中有 Angular ,我将其用作静态文件。我将展示一些代码片段。 请我基于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>



最佳答案

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

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

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

这将使 Angular 在刷新时不会重定向到基本 URL

关于javascript - Angular 路由通过手动刷新或直接输入 url 进入主页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56885656/

相关文章:

javascript - 我如何检查 object.property 是在 Angular 2 中定义的?

angular - 在 Typescript 中的映射内部分配 Observable 时出现未定义问题

javascript - Html 提交表单,但保持在同一页面上

javascript - 未捕获的语法错误 : Unexpected token ) on line 5

javascript - 选择表数据(对象数组)JS的高性能方法

javascript - 堆积条形图的 d3 示例到 jsfiddle

node.js - Nodejs 中定期检索访问 key 的代码片段

javascript - Mongoose 尝试使用 Promise 处理预保存错误

javascript - 使用 Vue-cli/Webpack 通过一个命令启动客户端和服务器

javascript - 将自定义图像添加到可重用的 Angular 组件