我已将 Angular 11 应用程序托管到远程服务器上的 IIS。 应用程序路由对于我的 3 个路由中的 2 个运行良好。 前两个是从登录页面到“主页”页面以及从“主页”到“设计”页面的路由(单击主页也可以返回主页)。这两条路线可通过
访问this.router.navigate(['design']);
或
this.router.navigate(['home']);
从“设计”页面转到“预览”页面是行不通的。此路由是通过打开一个新窗口(浏览器中的新选项卡)来完成的
window.open('preview');
404 - 未找到文件或目录。 您正在查找的资源可能已被删除、更名或暂时不可用。
我读过,我应该将我的 IIS 配置为 URL 重写,但我不明白这个概念。 当从 VSCode 和 ngserve
执行此操作时,这一切都有效我的问题是,我缺少什么,是 IIS 配置吗?如果是,我通过 URL 重写得到什么 - 当我瞄准正确的 URL - http:// 时,MS 网页上的示例似乎与我无关/servername:port/preview 并收到 404 错误
或者是 window.open() 的问题?
尝试刷新非登录页面时,出现相同的 404 - 文件未找到错误。
我已阅读此线程,但我仍然不明白 URL 重写的必要性
这是app-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服务器返回/
加载 Angular 应用程序后,如果用户单击指向 /home 路由的路由器链接,Angular 将更改用户浏览器上的 url 并显示所选路由的组件,但浏览器不会创建 HTTP请求服务器上不存在的 /home 资源。浏览器显示的页面仍然是index.html。
但是当用户打开 /home 的新选项卡或按 F5 时,浏览器会向服务器请求 /home 资源,因为 /home 资源不存在,因此会返回 404 错误。
为了使应用程序正常工作,服务器需要通过返回index.html来响应对/home的请求。这样,当用户请求 /home 时,他会加载 Angular 应用程序,一旦将其加载到浏览器上,Angular 路由就会启动并显示 home 组件。
因此服务器需要返回index.html,但是Angular应用程序将使用index.html之外的其他资源,例如脚本,样式,图像,API,... 因此,仅当服务器不是对这些资源之一的请求时,才需要返回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>
当请求不匹配文件、目录且不以 /api 开头时,这些规则将使服务器返回资源 /(即 index.html)
无需重写 url,也可以通过将此行为直接编码到 Web 服务器中来完成此操作。在 aspnet core 中,这是通过 SpaStaticFiles 中间件完成的。
当您使用 ngserve 运行应用程序时,Angular cli 会启动一个已配置为执行 URL 重写的 Web 服务器。这就是为什么你的本地主机没有这个问题。
[routerLink]=‘/preview’ href=‘_blank’
在标签内应将您带到新选项卡中的正确路线
https://stackoverflow.com/a/57906512/8511303
这个解决方案对我有用。 只需将 web.config 移动到
src
文件夹即可。
并将其添加到 assets
。