【问题标题】:Cannot navigate to specified url if using Ng build如果使用 Ng build,则无法导航到指定的 url
【发布时间】:2017-06-21 06:22:07
【问题描述】:

我有我的 Angular 2 应用程序。我在 localhost 上运行。我在 url:localhost:5050 上有一个页面。如果我直接粘贴 url localhost:5050/test2 我在浏览器页面上收到错误“Cannot GET /test2” 这是我的路线

        { path: '', component: Test1Component },
        { path: 'test2', component: Test2Component },
        { path: 'test3', component: test3lComponent},

我不知道这个问题。我必须向客户发送一个链接(链接包含特定页面https://xx.xx.xx.xx/test2 的应用程序的url)。因此客户可以从链接导航到实际页面

更新:如果我使用 ng serve 并在 localhost:4200/test2 上运行它可以工作(它路由) 但是如果我使用 ng build 并在 localhost:5050/test2 上运行,我会得到 Cannot GET /test2 错误

下面是我的 server.js

    app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, 
   Content-Type, Accept, X-Trace-Id, X-Egress-Time, X-Ingress-Time");
   res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
next();
  });
  app.use(express.static(path.join(__dirname, '/dist')));

【问题讨论】:

  • Test2Component 中发生了什么? localhost:5050/test2 工作正常吗?如果是这样,您是否尝试过将 test3lComponent 代替 Test2Component 作为测试?
  • 应用程序的流程很好。我可以按顺序正确地从test1到test2到test3。但是当我直接想从浏览器导航到 localhost:5050/test2 时,我得到了错误。它的主要任务是通过指定组件的直接路径从 url 导航到任何页面
  • 好的,我知道了,你的路由器文件的其余部分是什么样的?
  • @BenjiLees 下面是我的路线,我的索引是 const appRoutes: Routes = [ { path: '', component: Test1Component}, { path: 'test2',组件:Test2Component },{路径:'Test3:id',组件:Test3Component },];
  • 我正在使用节点 app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access -Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Trace-Id, X-Egress-Time, X-Ingress-Time"); res.header('Access- Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); next(); });

标签: routing angular2-routing angular-cli


【解决方案1】:

我认为这实际上是您的服务器的一个问题,您当前正在向您的服务器发送一个 get 请求,该请求试图匹配不存在的 localhost:5050/test2。如果您更改应用程序以使所有未知路由都返回基本应用程序 Angular 将处理其余部分并根据 url 重新路由您的应用程序。

即表达类似的东西:

  app.use('/*', express.static('./dist/index.html'));

【讨论】:

  • 我已经阅读并尝试了几种不同的方式,这就是我的节点中的情况app.use('*',express.static(path.join(__dirname, '/dist')));我尝试了你告诉我的我收到了这个错误Uncaught SyntaxError: Unexpected token <
  • 你有没有想过使用像express-http-proxy这样的代理?
【解决方案2】:

我遇到了同样的问题,并按照以下链接中的文档进行操作。

https://angular.io/guide/deployment

我正在使用 Apache 服务器,因此修改了 .htaccess 中的重新布线规则

RewriteEngine On
    # If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

我希望这会有所帮助..

【讨论】:

    猜你喜欢
    • 2016-06-02
    • 2021-02-02
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多