简体   繁体   中英

Angular webpack - how do you rewrite URLs?

As I understand it from other SO posts, if you try to browse directly to a URL on Angular it will fail with a 404 because that is handled by the backend webserver. In Angular's case, the default webserver is webpack.

The official documentation lists how to setup URL rewriting for several applications but it seems like they don't provide an example for webpack.

I've seen posts about using ng eject but when I try to do that I receive:

npx -p @angular/cli ng eject
The specified command ("eject") is invalid. For a list of available options,
run "ng help".

Did you mean "e2e"?

How does one tell webpack to rewrite a URL?

I think you're getting confused.

Angular is a frontend framework and there's no backend URL redirection . Angular-CLI uses webpack as it's bundler and sets up a development server which ALWAYS loads / or /index.html .

Once that is done, the Single Page App boots up and the in-app (angular router) takes over and starts loading (or lazy-loading if you configured) the different modules and components based on where you are. All that happens on the client side; the user's browser.

Of course when a user types a custom URL on the browser that's going to load the "desired" HTML document on the server: but in Angular it's different. There's just an index.html that "evolves" into the desired page.

So how do we solve the problem of loading the desired page if the user typed http://host.com/a/nested/url ? Because that's gonna return 404 if we just have an index.html file at the root

Well depends on the webserver you're using and solution varies whether it's an NGINX, IIS, Phoenix... You name it.

Essentially all solutions consist in indicating the webserver to always serve the built index.html file by angular. Send that back to the browser and let the angular router figure out which components to load based off that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM