Angular - 构建后未处理的导航错误
Angular - Unhandled Navigation Error after building
我通过以下命令构建了一个简单的 angular 应用程序,其中包含 2 个路由:
ng build --aot --prod --base-href ./
然后我打开位于 dist
文件夹中的 index.html
文件,应用程序运行但路由不起作用,我在控制台上收到以下警告:
希望能很好地解释我的问题。提前致谢。
使用 Angular 路由引擎将强制您在某些服务器上托管您的应用程序(例如 IIS, NodeJS 等)
没有路由的简单 angular 应用程序可以 运行 无需在服务器上托管它。
来自Angular docs:
Angular apps are perfect candidates for serving with a simple static HTML server. You don't need a server-side engine to dynamically compose application pages because Angular does that on the client-side.
If the app uses the Angular router, you must configure the server to return the application's host page (index.html) when asked for a file that it does not have.
Angular 如果您使用哈希路由并在 index.html.
中按如下方式定义基本 href,则路由有效
<base href="#">
在我的例子中,我会得到:
Unhandled Navigation Error: main.af3eff424835a3d5642f.js:1
因为我的基础 url 设置为 https://
<base href="https://example.com" />
但我是通过 http://
加载网站的
http://example.com
解决方案是使用 https:// url 或更改基础 url 以允许通过 http 访问。
app/module.ts:
import { LocationStrategy, HashLocationStrategy} from '@angular/common';
@NgModule({
...
],
providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }]
})
正如 所说,使用 Angular 路由引擎将迫使您在某些服务器上托管您的应用程序。
在部署应用程序之前,仅在演示情况下,您可以设置 RouterModule.forRoot(routes, { useHash: true })
并使用 hash 进行路由,以避免将您的应用程序托管在服务器中。
我通过以下命令构建了一个简单的 angular 应用程序,其中包含 2 个路由:
ng build --aot --prod --base-href ./
然后我打开位于 dist
文件夹中的 index.html
文件,应用程序运行但路由不起作用,我在控制台上收到以下警告:
希望能很好地解释我的问题。提前致谢。
使用 Angular 路由引擎将强制您在某些服务器上托管您的应用程序(例如 IIS, NodeJS 等)
没有路由的简单 angular 应用程序可以 运行 无需在服务器上托管它。
来自Angular docs:
Angular apps are perfect candidates for serving with a simple static HTML server. You don't need a server-side engine to dynamically compose application pages because Angular does that on the client-side.
If the app uses the Angular router, you must configure the server to return the application's host page (index.html) when asked for a file that it does not have.
Angular 如果您使用哈希路由并在 index.html.
中按如下方式定义基本 href,则路由有效<base href="#">
在我的例子中,我会得到:
Unhandled Navigation Error: main.af3eff424835a3d5642f.js:1
因为我的基础 url 设置为 https://
<base href="https://example.com" />
但我是通过 http://
加载网站的http://example.com
解决方案是使用 https:// url 或更改基础 url 以允许通过 http 访问。
app/module.ts:
import { LocationStrategy, HashLocationStrategy} from '@angular/common';
@NgModule({
...
],
providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }]
})
正如
在部署应用程序之前,仅在演示情况下,您可以设置 RouterModule.forRoot(routes, { useHash: true })
并使用 hash 进行路由,以避免将您的应用程序托管在服务器中。