如何防止 Angular 刷新页面时出现 404 not found 错误?

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

我有一个 Angular 项目,当我将其上传到全局服务器上时,当我刷新页面时,它会返回 404 未找到错误。我怎样才能防止这种情况发生?

这是我的routing.component.ts

import { RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';

import { PagesComponent } from './pages.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ECommerceComponent } from './e-commerce/e-commerce.component';
import { NotFoundComponent } from './miscellaneous/not-found/not-found.component';
import { createFalse } from 'typescript';

const routes: Routes = [
  
  
  {

  path: '',
  component: PagesComponent,
  children: [
    {
      path: 'dashboard',
      component: ECommerceComponent,
      
    },
    {
      path: 'iot-dashboard',
      component: DashboardComponent,
      
    },
    
    
    {
      path: '',
      redirectTo: 'iot-dashboard',
      pathMatch: 'full',
    },
    
    {
      path: '**',
      component: NotFoundComponent,
    },
  ],

}];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class PagesRoutingModule {
}
angular routes page-refresh
3个回答
3
投票

只需使用 Angular 的 HashLocationStrategy 即可。

RouterModule.forRoot(routes, {useHash: true});

1
投票

你必须在服务器上设置一个后备到index.html(你没有说哪一个是:Apache HTTPD?Nginx?): https://angular.io/guide/deployment#routed-apps-must-fallback-to-indexhtml


0
投票

如果使用 Apache 服务器,请在

.htaccess
旁边的新
index.html
文件中添加以下内容。

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

上次测试 2024 年。

原因: SPA 加载单个 HTML 文件并在用户与应用程序交互时动态更新内容,而无需重新加载整个页面。 React、Angular 和 Vue.js 等框架通常用于构建 SPA。 URL 由浏览器解释以加载

example.org
,然后 SPA 的 JavaScript 代码处理
path/component
部分以显示适当的内容。 服务器只需要提供初始 HTML 文件,SPA 处理客户端的路由。

如果给定的路径不是文件名或目录,

.htaccess
有助于回退到index.html。

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