Rob*_*ert 27 angular2-routing angular
我正在关注Angular 2路由示例.使用"精简"网络服务器我可以从根和深层链接工作导航,但是使用Apache我可以从根导航,但是当跟随链接指向路由时会得到404 Not Found错误.
例如,以下URL对npm由端口3000启动的"lite"Web服务器起作用.
http://localhost:3000/crisis-center/2
Run Code Online (Sandbox Code Playgroud)
但是在端口80上运行Apache的下一个URL失败了.
http://localhost/crisis-center/2
The requested URL /crisis-center/2 was not found on this server.
Run Code Online (Sandbox Code Playgroud)
我确实尝试了一些针对类似Angular 1问题推荐的.htaccess解决方案,但没有运气.如果有人在Apache上有Angular 2路由和深层链接工作,请告诉我你是如何实现的.
@RouteConfig([
{ // Crisis Center child route
path: '/crisis-center/...',
name: 'CrisisCenter',
component: CrisisCenterComponent,
useAsDefault: true
},
{path: '/heroes', name: 'Heroes', component: HeroListComponent},
{path: '/hero/:id', name: 'HeroDetail', component: HeroDetailComponent},
{path: '/disaster', name: 'Asteroid', redirectTo: ['CrisisCenter', 'CrisisDetail', {id:3}]}
])
Run Code Online (Sandbox Code Playgroud)
Boot.ts
import {bootstrap} from 'angular2/platform/browser';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {AppComponent} from './app.component';
bootstrap(AppComponent, [ROUTER_PROVIDERS]);
Run Code Online (Sandbox Code Playgroud)
Rei*_*sma 48
因为上面的答案并没有真正回答你是否想要它与Apache一起工作的问题.HashLocationStrategy仍然是一个选项,但如果您希望它在Apache上工作,则需要执行以下操作:
.htaccess在与您相同的位置创建一个新文件index.html.以下代码将在里面:
<IfModule mod_rewrite.c>
Options Indexes FollowSymLinks
RewriteEngine On
RewriteBase /crisis-center/
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.html [L]
</IfModule>
Run Code Online (Sandbox Code Playgroud)
(注意,在问题<base href="/crises-center/">内部index.html应该与RewriteBase相同)
答案改编自问题+来自Angular 2路由和直接访问特定路由的答案 :如何配置Apache?
对于那些在Apache上运行的人来说,使用这个.htaccess
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*) /index.html [NC,L]
</IfModule>
Run Code Online (Sandbox Code Playgroud)
如果仍然出现错误,请运行以下两个命令:
sudo a2enmod rewrite
sudo systemctl restart apache2
Run Code Online (Sandbox Code Playgroud)
对于app.routes.module.ts中的angular4 / angular,请如下使用useHash,
@NgModule({
imports: [RouterModule.forRoot(routes, {useHash: true})],
exports: [RouterModule]
})
Run Code Online (Sandbox Code Playgroud)
你必须让你的服务器处理返回index.html的所有路由或使用HashLocationStrategy
(https://angular.io/docs/ts/latest/api/common/index/HashLocationStrategy-class.html)
看一眼:
使用 HTML5 路由时 Angular 2 的 Router 是否损坏?
| 归档时间: |
|
| 查看次数: |
33315 次 |
| 最近记录: |