【问题标题】:Angular-Routing not working in Cloud, but on localhostAngular-Routing 在云中不起作用,但在 localhost
【发布时间】:2019-08-07 12:27:56
【问题描述】:

我建立了一个包含几个组件的 Angular 网站。当使用ng serve 并在 localhost 上浏览时,路由工作得很好。但是当部署在云上时,只有起始页面在工作。路由到任何其他组件都不起作用,我收到错误: 404 Not Foundnginx/1.16.0.

我尝试使用 pathMatch: 'full' 等方法并创建一个启用 pushstate 的静态文件。

我也在使用<base href="/">

应用路由模块:

const routes: Routes = [
  { path: '', component: IndexComponent, pathMatch : 'full'},
  { path: 'login', component: StartComponent, pathMatch : 'full'},
  { path: 'register', component: RegisterComponent, pathMatch: 'full'},
  { path: 'forgot', component: ServiceComponent, pathMatch: 'full'},
  { path: 'impressum', component: ImpComponent, pathMatch: 'full'}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
export const routingComponents = [IndexComponent, StartComponent]

nginx 配置:

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    server {
        listen 80;
        server_name  localhost;

        root   /usr/share/nginx/html;
        index  index.html index.htm;
        include /etc/nginx/mime.types;

        gzip on;
        gzip_min_length 1000;
        gzip_proxied expired no-cache no-store private auth;
        gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;

        location / {
            try_files $uri $uri/ /index.html;
        }
    }
}

我不明白为什么 localhost 和服务器端路由存在差异以及如何修复它。

【问题讨论】:

  • 确保您为您的应用设置了正确的<base href="/">
  • 我已经这样做了
  • 我在 apache 服务器上遇到了类似的问题,按照以下方式解决了。可能这有帮助:joeljoseph.net/…
  • 您需要将服务器设置为将非资产请求重定向到您应用的index.html。目前,它正在尝试在您请求的 URL 处加载文件,而不是允许 Angular 处理路由。
  • 感谢您的回复。请您详细解释一下好吗?

标签: html css angular nginx angular-routing


【解决方案1】:

提供者:[ {provide: LocationStrategy, useClass: HashLocationStrategy} ]

在 app.module.ts 中

Angular 定位策略在这里:https://angular.io/api/common/LocationStrategy 这是哈希策略。正如@WillAlexander 所说,服务器正在尝试处理路由,并试图根据路由在文件结构中定位文件,而不是让 Angular 处理路由。这是 Angular 初学者的常见问题,其他策略可以在我提供的链接以及此处找到:https://angular.io/guide/deployment。希望对您有所帮助。

【讨论】:

  • 这修复了我的项目但破坏了我的自尊/s
猜你喜欢
  • 2013-02-12
  • 1970-01-01
  • 2016-01-01
  • 2020-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
  • 1970-01-01
相关资源
最近更新 更多