How to make Angular 2 Router work by rewriting the URL in deployed app?

扶醉桌前 提交于 2019-12-10 15:45:37

问题


I'm now finishing my Angular 2 Application and I'm wondering how to host it.

I've just tried to build the app on my localhost and actually everything seems to work fine, expect the Router of the app. I can't access routes by rewriting the URL because it's probably looking for some files and .htaccess RewriteRules, rather than routes. It's important for me to be able to access the routes by rewriting the URL, because I don't want to have [routerLink]s for my admin panel and some other stuff to be public (seen as a hyper-link).

To be more specific... When I visit http://localhost/FinalApp/ it uses router to navigate me to http://localhost/FinalApp/list/page/1 so the list/page/1 is add by the Angular 2 Router. All [routerLink]s are working correctly, and navigate me to eg. http://localhost/FinalAll/list/category/3 when I click them, but when I'm rewriting the URL manually to get to the admin panel (I'm adding admin to my base http://localhost/FinalApp/, so the final URL looks like http://localhost/FinalApp/admin) it shows me 404 Error (not Router's default route, but the server-side 404).

I want to be able to manually rewrite the URL and use Angular 2 Router.

Am I missing something or is it just impossible?


回答1:


This problem is solved by implementing HashLocationStrategy which adds # to all your routes: http://localhost/FinalApp/list/page/1 becomes http://localhost/#/FinalApp/list/page/1. You achieve this by adding HashLocationStrategy to AppModule providers:

{ provide: LocationStrategy, useClass: HashLocationStrategy }

You need to import LocationStrategy and HashLocationStrategy from @angular/common:

import { LocationStrategy, HashLocationStrategy } from '@angular/common';

If you are using RC4 or lower, you add this to your bootstrap method:

bootstrap(
AppComponent,
    [
        { provide: LocationStrategy, useClass: HashLocationStrategy }
    ]);



回答2:


As you said, this is due to server-side routing. Using the link href, the browser is making a request to the server where you're app is hosted. If you haven't set your web server to route desired paths to your single page app, it's going to look in the system for something on the server stored at http://localhost/FinalApp/admin. If you use url rewriting to maintain the url in the browser, but serve the app, the app will then do all the routing once it loads. Here's a trivial and untested example:

Example using apache rewrite

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(/.*)$ /index.html [L]


来源:https://stackoverflow.com/questions/39649220/how-to-make-angular-2-router-work-by-rewriting-the-url-in-deployed-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!