我有一个由 Node.js 服务器提供服务的 Angular 应用程序。手动刷新或直接输入 url/xyz 或/abc 后,如下例所示。我看到它被定向到主页。
例如:我单击导航按钮(xyz 和 abc),它会将我带到 https://mywebsite/xyz和 https://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/