用Koajs为angular2设置路由的正确方法是什么 [英] What's the right way to set routing for angular2 with koajs

查看:101
本文介绍了用Koajs为angular2设置路由的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是angular2和koajs的新手.也许这是一个愚蠢的问题.

I'm a newbie to angular2 and koajs. Maybe it's a silly question.

我有一个angular2应用,其路由表如下:

I have an angular2 app with a routing table as below:

const appRoutes: Routes = [
  {
    path: 'pats/report/settings',
    component: PatsReportSettingsComponent
  },
  {
    path: 'pats/report/:id',
    component: PatsReportComponent,
    pathMatch: 'full'
  },
  {
    path: 'pats/report/login',
    component: PatsLoginComponent,
    pathMatch: 'full'
  },
  {
    path: '.',
    redirectTo: 'pats/report/login',
    pathMatch: 'full'
  },      
  {
    path: '**',
    component: Pats404PageComponent,
    pathMatch: 'full'
  },
];

如果用户通过根网址( http://localhost:3000 )访问我们的应用,则导航至子级页面(例如: http://localhost:3000/pats/report/settings ),一切都是很好,因为angular2应用程序将在内部处理子页面导航,并且不会向后端发出http请求.

If user access our app via the root url (http://localhost:3000), then navigate to a child page (eg: http://localhost:3000/pats/report/settings), everything is fine since angular2 app will deal with the child page navigation internally and will not issue a http request to backend.

但是,如果用户直接使用子页面网址访问我们的应用,例如: http://localhost:3000/pats/report/settings ,后端koajs应用将以404状态响应,因为它在后端不存在路径"pats/report/settings"的路由.

But if user access our app with child page url directly, eg: http://localhost:3000/pats/report/settings, the backend koajs app will response with 404 status since it does not exist a route for path 'pats/report/settings' at the backend.

什么是解决此问题的正确方法?

我应该为后端路由器中的所有客户端子页面路径添加路由并使用index.html进行响应吗?

推荐答案

我不知道Koajs,但是您需要一些中间件.您的后端需要将这些请求重定向到localhost:3000/,但请保留原样的URL,以便angular可以发挥作用!

I dont know Koajs, but you need some middleware. Your backend needs to redirect those request to localhost:3000/ but let the URL as it is, so that angular can do its magic!

请参阅以下有关koajs的其他软件包:

See this additional packages for koajs:

  • koa-repath
  • rewrite

另一个选项:使用Hashbang-URL! Angular2 URL样式

The other option: Use Hashbang-URLs ! Angular2 URL-Styles

这篇关于用Koajs为angular2设置路由的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆