【问题标题】:Angular 2 Router: Cannot match any routesAngular 2 路由器:无法匹配任何路由
【发布时间】:2017-02-12 21:46:46
【问题描述】:

在我的浏览器中尝试加载 localhost:3000/verifyemail 时,我收到错误:

错误:无法匹配任何路由

我已经阅读了关于此的其他 SO 问题,并验证了以下内容:

  • Angular2:2.3.1默认使用Path Location Strategy,我没改过。我不喜欢使用哈希定位策略
  • 我已经为 HTML5 pushState 配置了我的 Nodejs 服务器(server.js 在下面)

    // Parsers for POST data
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    
    // Point static path to dist
    app.use(express.static(path.join(__dirname, 'dist')));
    
    // Get API routes
    const api = require('./src/server/routes/api.js');
    
    // Set api routes
    app.use('/api', api);
    
    // Catch all other routes and return the index file
    app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'dist/index.html'));
    });
    
    const port = process.env.PORT || '3000';
    app.set('port', port);
    
    const server = http.createServer(app);
    server.listen(port, () => console.log(`API running on localhost:${port}`));
    
  • 我的 index.html 中 <head> 的顶部有 <base href="/">

  • 我设置了默认和包罗万​​象的路线

    const appRoutes: Routes = [
      { path: 'home',
        outlet: 'full-page',
        component: DefaultLandingPageComponent
      },
    
      { path: 'verifyemail',
        outlet: 'full-page',
        component: EmailVerificationComponent
      },
    
      { path: '',
        redirectTo: '/home',
        pathMatch: 'full'
      },
    
      { path: '**',
        outlet: 'full-page',
        component: DefaultLandingPageComponent
      }
     ];
    
  • 我已将路由器模块导入到我的 app.module.ts 中,并在我的 app.component.html 文件中包含了一个路由器插座

    //in app.module.ts:
    @NgModule({
      ...
      imports: [
        ...
        RouterModule.forRoot(appRoutes)
      ]
      ...
      });
    
    //in app.component.html
    import { RouterModule, Routes } from '@angular/router';
    

非常感谢谁能帮我解决这个问题!

更新 1 由于 Günter Zöchbauer 在下面的 cmets 中的观察,我已经从路由和路由器插座中删除了所有名称

更新 2 在 localhost:4200/verifyemail 上一切正常,通过ng serve 运行。 使用通过node server.js运行的localhost:3000/verifyemail 时问题仍然存在

【问题讨论】:

    标签: node.js angular angular2-routing


    【解决方案1】:

    每个路由都需要一个将组件添加到未命名插座的路由。 已命名的 outlet 只能与未命名的 outlet 一起使用,不能代替。

    【讨论】:

    • 非常感谢您的帮助 - 这可能是个问题,但仍然无法正常工作。我从路由和路由器出口中删除了名称属性,现在读取为<router-outlet></router-outlet>。服务器重新加载正在工作 - 如果我将 res.sendFile 更改为 index.html 以外的任何其他文件,它将正确执行。问题是当它被重定向到 index.html 然后找不到任何路由
    • 抱歉,无法帮助您设置 node.js 服务器。
    • 谢谢 - 服务器似乎工作正常,所以我认为问题出在角度方面。我的角度代码中的其他任何内容都可能是一个问题吗?感谢您的帮助
    • 如果你用RouterModule.forRoot(appRoutes, {useHash: true})还是不行,那就是Angular代码问题,否则是服务器问题。
    • 看起来我们有一个角度问题 - 我用 RouterModule.forRoot(appRoutes, {useHash: true}) 替换了 RouterModule.forRoot(appRoutes) 并且我收到了同样的错误
    猜你喜欢
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2017-09-25
    相关资源
    最近更新 更多