Angular HTML5 URLs - Server Configuration

I read that AngularJS uses hashbang URLs by default, but that is not an advantage, so HTML5 URLs should be used. To configure this behavior on the client side, you must do the following:

... $locationProvider.html5Mode(true); ... 

On the server side, you also need to make some settings - since I realized that URL requests should be configured, so the page with ng-app inside (the start page - for example, index.html) should be delivered to the client. URLs that provide static resources (CSS, images, AngularJS scores, etc.) and URLs that are used for CRUD URLs (such as RESTful URLs) are excluded.

My question is not how to configure this behavior on the server side (e.g. for String Boot with an embedded server inside)?

And one more question: if you distinguish between static resources (e.g. ... / static / ..) and CRUD URLs (e.g. ... / database / ...) in our AngularJS application?

Thanks a lot!

0
source share
2 answers

In Spring Boot, you can configure a catch-all controller like this:

 @Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.setOrder(Ordered.LOWEST_PRECEDENCE); registry.addViewController("/**").setViewName("forward:/index.html"); } } 

This redirects all requests that are not otherwise processed by index.html. setOrder(Ordered.LOWEST_PRECEDENCE) used to ensure that this forwarding of the entire stop is applied only after no other route is found.

However, now all resource searches are also routed through this view controller (since WebMvcAutoConfiguration checks for the presence of a path template before applying the default resource handler).

One possible fix is ​​to set a static path template in application.properties to enable verification of the file extension:

 spring.mvc.static-path-pattern = /**.* 

This only works if your angular routes do not contain any extensions. Another way is to completely disable Spring boot resource processing ( spring.resources.addMappings = false ) and substitute your own.

+2
source

Basically you want to serve /index.html (your Angular app) for all 404 with an accept accept text/html value. Angular will pick up the route and behave as expected. Try to cope with this at the web server level, if you can, it will be more effective than processing it in any framework that you use.

For another question, some sites use a similar subdomain, such as api.example.com , and some sites use a path, such as example.com/api . This is basically not a problem, although you will have to configure CORS if you go with the subdomain.

0
source

Source: https://habr.com/ru/post/988709/


All Articles