允许直接访问路由中定义的 angular 应用程序 url(浏览器导航)

Allow direct access to angular application url (browser nagivation) defined in routes

我已经构建了我的 angular12 应用程序 运行 以下命令行:

ng build --configuration production

在这个阶段它起作用了。 现在我遇到了一些问题: 默认页面是 http://localhost 一旦用户被重定向到带有 lang 参数的主页。用户被重定向到:

http://localhost/en/home

现在,这个站点应该有几个入口点。我的意思是用户不仅可以直接到达主页,还可以直接到达搜索页面。这个搜索页面可以是:

http://localhost/en/search

http://localhost/en/search?surname=John&name=Doe

如果我直接访问此页面,则会出现 404 错误。 我的站点结构如下

App (component, module, routing)
|_ site (component, module, routing)
      |_ home (component, module, routing)
      |_ info (component, module, routing)
      |_ search (component, module, routing)

在我的应用程序路由中,我重定向到站点组件并传递有关 lang 的信息。

const routes: Routes = [
  {
    path: WebsiteLanguage.English,
    loadChildren: () => import ("./components/site/site.en.module").then(m => m.SiteEnModule)
  }, // lazy loading the English site module
  {
    path: WebsiteLanguage.French,
    loadChildren: () => import ("./components/site/site.fr.module").then(m => m.SiteFrModule)
  },   // lazy loading the French site module
  {
    path: '**',
    redirectTo: WebsiteLanguage.English
  }   // redirecting to default route in case of any other prefix
];

在站点路由模块中:

const routes: Routes = [
  { path: '',
    component: SiteComponent,
    children: [
      {
        path: 'home',
        loadChildren: () => import ("./pages/home/home.module")
          .then(m => m.HomeModule)
      },
      {
        path: 'info',
        loadChildren: () => import ("./pages/info/info.module")
          .then(m => m.InfoModule)
      },
      {
        path:'sandbox',
        loadChildren: () => import ("./pages/sandbox/sandbox.module")
          .then(m => m.SandboxModule)
      },
      {
        path: 'search',
        loadChildren: () => import ("./pages/search-document/search-document.module")
          .then(m => m.SearchDocumentModule)
      },
      {
        path: '',
        pathMatch: 'full',
        redirectTo: 'home'
      },
    ]
  }
]

终于在我的搜索路由模块中:

const routes: Routes = [
  {
    path: '',
    component: SearchDocumentComponent,
  },
];

使用导航我可以访问页面

在这个阶段,我用我的项目文件夹“ng-project”生成了一个 dist 文件夹。我想在 wamp 服务器上测试它,然后将 ng-project 文件夹复制到我的 www 根 html 文件夹中。到目前为止,还不错。

现在当我尝试打开 link: http://localhost/ng-project 我看到主页但是:

我通过将网站置于根级别来解决这个问题。如果有办法解决这个问题就好了。

如果我刷新,出现 404 错误:

您应该创建一个 .htaccess 文件,将所有初始请求重定向到主 Angular index.html 文件。 您可以在此处找到示例和详细说明:https://angular.io/guide/deployment#routed-apps-must-fallback-to-indexhtml