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

时间:2021-01-21 13:15:26

标签: angular routes page-refresh

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

那是我的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 {
}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

只需使用 angular 的 HashLocationStrategy。

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