Angular 11 - 打开新标签页时出现 404 错误

Angular 11 - Error 404 when opening new tab

我已将我的 Angular 11 应用程序托管到远程服务器上的 IIS。 应用程序路由适用于我的 3 个路由中的 2 个。 前两个是从登录页面到 'home' 页面以及从 'home' 到 'design' 页面的路由(单击主页也会让我返回主页)。这两条路线被

访问
this.router.navigate(['design']);

this.router.navigate(['home']);

从 'design' 页面转到 'preview' 页面不起作用。此路由是通过打开一个新的 Window(浏览器中的新选项卡)

完成的
window.open('preview');

404 - File or directory not found. The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.

我读到我应该将 IIS 配置为 URL Rewrite,但我不明白这个概念。 从 VSCode 和 ng serve

执行时,这一切都有效

我的问题是,我缺少什么,是 IIS 配置吗?如果是的话,我通过 URL 重写得到了什么 - 当我瞄准时,MS 网页上的示例似乎与我无关对于正确的 URL - http://servername:port/preview 并得到 404 错误
还是 window.open()?

的问题

我在尝试刷新不是登录页面的页面时遇到相同的 404 - 找不到文件错误。

我已经读过 this thread 但我仍然不明白需要 URL 重写

这是应用程序-routing.module.ts代码:

const routes: Routes = [
    {path: '', component: LoginComponent},
    {path: 'design', component: PaletaFormaComponent},
    {path: 'preview', component: PreviewFormaComponent},
    {path: 'home', component: FirstPageComponent},
  
];

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

Angular 应用程序是单页应用程序,这意味着整个应用程序位于单个页面中 index.html

当客户端浏览器请求 /index.html 资源时,它会加载 angular 应用程序。由于 index.html 被定义为默认页面,当客户端请求 /

时,此资源也将被 Web 服务器 returned

加载 angular 应用程序后,如果用户单击路由器 link 到 /home 路由,angular 将更改用户的 url浏览器并将显示所选路由的组件,但浏览器不会向服务器上不存在的 /home 资源发出 HTTP 请求。浏览器显示的页面还是index.html.

但是当用户打开 /home 的新选项卡或按 F5 时,浏览器会向服务器请求 /home 资源,因为它不存在,所以 return 出现 404 错误。

要使应用程序正常工作,服务器需要通过 returning index.html 响应对 /home 的请求。这样,当用户请求 /home 时,他会加载 angular 应用程序,一旦它被加载到浏览器上,angular 路由就会启动并显示 home 组件。

因此服务器需要 return index.html,但是 angular 应用程序将使用 index.html 以外的其他资源,例如脚本、样式、图像、API、. .. 所以服务器需要 return index.html 只有当它不是对这些资源之一的请求时。 一种方法是使用 URL 重写规则。在 IIS 中,您可以使用 :

  <rules>
    <rule name="Angular Routes" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
      </conditions>
      <action type="Rewrite" url="/" />
    </rule>

当请求不匹配文件、目录且不以 /[=46= 开头时,这些规则将使服务器 return 成为资源 /(因此 index.html) ]

这也可以在不 url 重写的情况下完成,方法是将此行为直接编码到 Web 服务器中。在 aspnet 核心中,这是通过 SpaStaticFiles 中间件完成的。

当您 运行 使用 ng serve 的应用程序时,angular cli 会启动一个已配置为执行 URL 重写的 Web 服务器。这就是为什么您的 localhost 没有这个问题。

[routerLink]=‘/preview’ href=‘_blank’

在你的标签内应该会把你带到新标签页中的正确路线