假设这是在具有Angular前端的Node服务器上处理所有路由的部分 . 当用户输入站点URL时,服务器将发送所有静态文件以供浏览器呈现 . 但是,我希望客户端处理某些路由而不是直接进入服务器 .
例如,如果我输入 www.exemple.com/page2 ,则会向服务器发送Get请求,但该路由不存在,因此请求只会挂起并最终导致错误 .
我希望Angular处理路由而不是自动进入服务器 . 我只是成功地将其用于localhost,其中Angular应用程序是从与服务器侦听的端口不同的端口提供的 . 任何人都可以告诉我如何实现这一目标吗?非常感谢 .
module.exports=function(app,dir){
app.use(express.json());
app.use(express.static(dir+'/dist/probeeshq'));
app.get('/',(req,res)=>{res.sendFile(path.join(dir));});
app.use('/auth', userAuth);
app.use('/api/me',userData);
app.use('/api/org',organization);
app.use('/api/messaging',messaging);
app.use('/api/search',search);
app.use(error);
}
这就是我在Angular中所拥有的
const routes: Routes = [
{ path:'', component: HomeComponent },
{ path:'project_gaea', component:ProjectGaeaComponent},
{ path:'dashboard', component: DashboardComponent ,canActivate:[AuthGuardService]},
{ path:'explore', component:ExploreComponent, canActivate:[AuthGuardService]},
{ path:'create', component: CreateComponent },
{ path:'user/:id', component:UserProfileComponent},
{ path:'**', component: PageNotFoundComponent}
];
2 回答
您可以通过实现Angular开箱即用的Route功能来实现此目的 . 实现此功能后,您只需将后端用作API即可 .
所以事实证明我应该像这样服务应用程序:
app.use('/', express.static(dir));
并且Express会在无法匹配服务器端的所有路由后让Angular处理所有路由 . dir只是Angular应用程序的路径 .