Node / Express中的路由和已部署的Angular无法正常工作

时间:2019-02-13 16:36:19

标签: node.js angular express routes

由Node with Express提供服务时,已部署的Angular应用上的路由不起作用。我知道这已经被问过了,但是我可能缺少一些东西,这使我发疯。

运行节点的“ 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/rubrichttps://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。我想念什么?

1 个答案:

答案 0 :(得分:1)

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

因为您没有在快速中间件中定义/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'));
});

这可能不是快递的最佳做法,您可以搜索其他解决方案,例如VueRouter建议将connect-history-api-fallback与快递配合使用。