我有一个 Angular 4 项目,当我从 localhost:4200/route-a
运行它时,它工作正常,当我刷新浏览器时,一切都按预期工作。但是,当我使用 ng build
构建它并从 apache 运行它时,导航到 localhost/route-a
会返回 404
。这是我的路由代码:
imports: [BrowserModule, HttpModule, FormsModule, RouterModule.forRoot([
{ path: 'home', component: HomeComponent },
{ path: 'route-a', component: RouteAComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
])]
最佳答案
这不是 Angular 的问题。你的apache设置有问题。 当您在 Angular 中使用 HTML5 模式(漂亮的 url)时,您将必须配置 Apache 以将服务器上不存在资源的所有请求发送到 index.html 文件。
这可以通过以下 .htaccess 配置来完成:
RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html
原因是当你尝试访问/route-a
时,apache服务器会默认尝试寻找目录route-a
和index.html内的文件。但是因为你没有那个目录,apache 会返回 404 错误。
但是通过告诉 apache,对于任何位置或文件不存在的请求。要发送已发送的 Angular html 文件,Angular 路由器会从那里获取它。
关于angular - 如何以 Angular 4 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44819308/