【问题标题】:angular2 with node routes issueangular2与节点路由问题
【发布时间】:2017-09-08 17:24:59
【问题描述】:

我目前正在使用 angular2,出于部署目的,我必须使用节点作为我的服务器。我被困在路线中

成功场景:

如果我使用 routerLink 导航到页面,它可以正常工作,节点可以很好地为它们服务

路线是:http://localhost:8080/sign-in --- 工作正常

失败场景: 如果我在地址栏中手动输入与上述相同的地址,则无法加载页面

即它卡在说 app-loading 是 index.html 和其他路由不起作用

index.js

const express = require('express');
const app = express();
var path = require("path");



app.use(express.static(__dirname + '/dist'));


app.get('/[^\.]+$', function(req, res) {
  console.log(__dirname+'/src/index.html')
  res.sendFile(path.join(__dirname+'/src/index.html'))
});
app.listen(process.env.PORT || 8080);

问题在于节点服务器无法提供页面,但我希望路由即使从地址栏也能正常工作,任何帮助将不胜感激 该应用适用于 生产模式,具有 angular 4

【问题讨论】:

    标签: node.js angular angular2-routing


    【解决方案1】:

    在您的 Angular 项目中:

    不要伪造使用 ng build 来构建您的项目。之后,你会看到一个新目录:dist 此目录包含您的 Angular 项目。

    在您的节点项目中:

    你必须在你的 Angular 项目中发送所有路由:

    // Send all other requests to the Angular app
    app.get('*', (req, res) => {
        res.sendFile(path.join(__dirname, 'yourprojectangular/dist/index.html'));
    });
    

    【讨论】:

      【解决方案2】:

      尝试使用 HashLocationStrategy 作为 LocationStrategy:

      import { HashLocationStrategy, LocationStrategy } from '@angular/common';
      
      @NgModule({
          // ...
          providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
          // ...
      })
      export class AppModule {}
      

      【讨论】:

      • 尝试把'/[^\.]+$'改成'/*'
      • 它可以工作,但 url 现在带有一个 hashbang,即 localhost:8080/#!/signin
      • 对用户来说似乎是不可见的
      • 是什么使它起作用? HashLocationStrategy 或将 '/[^\.]+$' 更改为 '/*' ?
      • 不使用这两个我现在可以通过添加 hashbang 来命中
      猜你喜欢
      • 1970-01-01
      • 2016-07-09
      • 2017-03-26
      • 2016-11-29
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      相关资源
      最近更新 更多