【问题标题】:Routes in Node/Express and deployed Angular not workingNode/Express 和部署的 Angular 中的路由不起作用
【发布时间】:2019-07-07 13:59:44
【问题描述】:

部署的 Angular 应用程序上的路由在由 Node 和 Express 提供服务时不起作用。我知道以前有人问过这个问题,但是我可能缺少一些让我发疯的东西。

Node运行的“express”文件夹中的文件结构大致如下:

express
├── controller.js
├── index.js
├── ngForm 
│   ...see below...
├── node_modules
│   ...
├── package.json
├── public
│   ├── file.json
│   └── rubric.html
├── router.js
├── ssl
    ├── cert.pem
    └── key.pem

Angular 项目在 ngForm 中:

ngForm 
├── angular.json
├── dist
│  └── rubric
│       ├── assets
│       ├── favicon.ico
│       ├── index.html
│       ├── main.js
│       ├── main.js.map
│       ├── polyfills.js
│       ├── polyfills.js.map
│       ├── runtime.js
│       ├── runtime.js.map
│       ├── styles.js
│       ├── styles.js.map
│       ├── vendor.js
│       └── vendor.js.map
├── e2e
├── node_modules
├── package.json
├── src
├── tsconfig.json
└── tslint.json

一些相关的Angular代码:

app.module.ts:

const appRoutes: Routes = [
  {path: '', redirectTo: '/rubric', pathMatch: 'full' }, 
  {path: 'rubric', component: RubricComponent},
  {path: 'rubricbuilder', component: RubricbuilderComponent},
  {path: '**', component: PageNotFoundComponent}
]

app.component.ts:

@Component({
  selector: 'app-root',
  styleUrls: ['app.component.scss'],
  template: `<router-outlet></router-outlet>`
})

相关的Node.js代码:

server.js:

app.use(express.static("ngForm/dist/rubric"));
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'ngForm/dist/rubric/index.html'));
});

我确实在 ngForm 中从 Angular 项目运行了 ng build,并且输出在 ngForm/dist 中。

在 AngularProject 中运行 ng serve 时,我可以导航到 https://localhost:4200/rubric 和 https://localhost:4200/rubricbuilder 。

从节点我只能到达https://localhost:8000/,它将url重定向/更改为https://localhost:8000/rubric,但我无法启动https://localhost:8000/rubric本身或https://localhost:8000/rubricbuilder。通过探索角度路线并重新运行构建,我可以在 / 路线上制作 express show rubricbuilder,这会将 url 更改为https://localhost:8000/rubricbuilder。我错过了什么?

【问题讨论】:

    标签: node.js angular express routes


    【解决方案1】:

    我对 Angular 不太熟悉,但这个问题与 VueRouter 有关。

    因为您没有在 express 中间件中定义 /rubric 路由器,所以您可能会收到类似 404 NOT FOUND 的错误。

    在 HTML5 历史模式下使用 SPA 路由器时,您需要对服务器进行额外配置,

    例如,在每条路线上发送您的 SPA:

    app.use(express.static("ngForm/dist/rubric"));
    app.use((req, res) => {
      res.sendFile(path.join(__dirname, 'ngForm/dist/rubric/index.html'));
    });
    

    这可能不是 express 的最佳实践,您可以搜索其他解决方案,例如 VueRouter 建议使用 connect-history-api-fallback 和 express。

    【讨论】:

    • 行得通!现在我意识到我的 .get 只为 / 设置路由,而你的 .sendFile 服务于 index.html,这听起来是正确的做法。让我检查一下这是否是 Node/Express 的最佳实践,我会接受你的回答
    • 实际上带有 app.use((req, res) => .. 的行我认为没有必要。这也会强制路由到 index.html,如果有其他路由这样的作为后端 API
    猜你喜欢
    • 2018-04-23
    • 2022-08-23
    • 2017-06-23
    • 2013-11-20
    • 2018-01-10
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多