【问题标题】:Not able to open a page directly angular无法直接打开页面
【发布时间】:2018-02-04 01:04:28
【问题描述】:

在本地主机上,一切正常,但是当我在 Heroku 页面上部署文件时,无法通过 URL 直接打开

无法获取 /profile

通过this.router.navigate(['/profile']); 完成重定向时的内部页面这工作正常我进入 url 页面但是当我直接打开时,错误
server.js 文件

const express = require('express');
 const app = express();
 app.use(express.static(__dirname + '/dist'));
 app.listen(process.env.PORT || 8080);

同样的错误图像也无法加载它们,我是否必须在此处再次定义路由,就像我在 app.module.ts 中定义的那样

 RouterModule.forRoot([
 { path: '', component: HomeComponent },
 { path: 'admin', component: AdminComponent,canActivate:[AdminAuthGaurd]},
 { path: 'profile', component: ProfileComponent},
 { path: 'accessdenied', component: NoAccessComponent},
 { path: '**', component: NotFoundComponent }
])

我该怎么做

app.get('*', (req, res) => {
this.router.navigate(['*']);
  });

因为我已经在我的 Angular 应用上处理了这些请求!
任何帮助都会非常感谢

【问题讨论】:

    标签: angular routing


    【解决方案1】:

    这很正常。在 Angular 中,您只有一个文件要提供 - index.html - 当您 GET www.yourdomain.com 时提供。因此,我们将 Angular 应用程序称为 SPA(单页应用程序)——我们确实需要提供一个页面,并且 Angular 应用程序路由应该在应用程序内部自行完成。

    当您尝试打开 /profile 时,您将离开 Angular 应用程序并到达 Express 应用程序范围,它没有任何路由来处理此类请求。如果你有这样的事情:

    const express = require('express');
    const app = express();
    app.use(express.static(__dirname + '/dist'));
    app.get('/profile', (req, res) => {
       // do something
    });
    app.listen(process.env.PORT || 8080);
    

    你会得到一些东西,但它会关闭 Angular 应用程序 (index.html)。

    您可以在docs 中阅读更多信息。

    阅读hashing strategy 并告诉我它是否对您有帮助。通过散列,您可以 GET

    www.yourdomain.com/#/profile
    

    并且页面永远不会被发送到服务器任何超过 URL 中的 # 的内容。如果你使用这样的策略,你应该保留原始的 Express 服务器代码。

    【讨论】:

    • 更新了我的问题,请检查
    • 更新了我的答案。
    【解决方案2】:

    您可以将 express 配置为始终提供 index.html,无论 url 是什么,这应该允许您从外部链接访问您的路线:

    //  all routes lead to to index.html
    let router = express.Router();
    router.get('*', (req, res) => {
      res.sendFile(path.join(DIR, 'index.html'));
    });
    this.express.use('*', router);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-27
      • 2014-12-20
      • 2015-01-26
      • 2014-08-19
      相关资源
      最近更新 更多