在部署项目(ng build)之后无法导航到Angular 5应用程序中的其他页面

问题描述 投票:0回答:1

当我使用以下命令测试我的Angular应用程序(v5)时:

ng serve --open

我可以导航到我的申请的任何注册路线。当我想在构建过程之后通过以下方式提供我的应用程序:

ng buildng build --prod

导航到任何路线后,我收到404错误。如果要阅读official tutorial,项目部署不应该有任何复杂的操作。

我已经进行了搜索并找到了在build命令中添加--base-href=/选项的建议,但也没有成功。

我正在使用下一个HTTP服务器:https://www.npmjs.com/package/http-server

可能的问题是:

Q1:你如何为Angular应用程序提供服务?

A1:在应用程序目录中使用NPM-package的http-server --cors命令,因此--base-href正确引用

Q2:您的路由配置是什么(源代码)?

A2:我的路由非常简单,因为我正在学习Angular v5教程,所以不要指望一些特别的东西,源代码是下一个:

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SalesComponent }       from './sales/sales.component';
import { ConsumersComponent }   from './consumers/consumers.component';

const routes: Routes = [
    { path: 'consumers' , component: ConsumersComponent },
    { path: 'sales', component: SalesComponent }
];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
})

export class AppRoutingModule { }

app.modude.ts文件(@NgModule中的imports:)中提供了AppRoutingModule。

问题3:您的Angular应用程序是否依赖于后端(服务器端应用程序)?

A3:没有。它只有用于数据模拟的模拟对象。它们被定义为分离类中的静态数据。我没有去官方网站上的Angular教程那么远。只是想用我最喜欢的小型HTTP服务器来提供ng build --prod版本。

因此,在使用ng serve命令时,我可以导航到其他页面,但在构建项目后我不能这样做。教程提供了描述,我可以将构建的文件作为静态的文件提供给任何HTTP服务器,但对我来说没有成功。

我怎样才能解决我的问题?

谢谢

angular deployment build routing production
1个回答
0
投票

由于official deployment guide,我已经解决了我的问题。

您应该将HTTP服务器配置为遵循前端控制器模式。我使用下一个配置使用nginx服务器测试了它:

server {
    listen 80 default_server;
    root /var/www/html;
    index index.html index.htm;
    server_name localhost;
    location / {
        try_files $uri $uri/ /index.html;        
    }
}   

现在一切都很好。

如果您使用Apache服务器或.htaccess文件,如果IIS是您的HTTP服务器等,您可以使用web.config文件执行相同操作。

© www.soinside.com 2019 - 2024. All rights reserved.