Angular 2 Routing Does Not Work When Deployed to Http Server

前端 未结 18 1907
误落风尘
误落风尘 2020-12-07 22:42

I am going to develop a simple Angular 2 application. I have created a project with routing, using Angular CLI and added several components to the app using \'ng generate co

18条回答
  •  既然无缘
    2020-12-07 23:06

    I also faced this issue and found a solution that does not require HashLocationStrategy solution.

    Issue is, a server like tomcat looks for a actual folder (for eg : /about ) which does not exist in angular app, as its a single page application. So every request needs to be redirected to index.html.

    Easiest way to fix this issue is to add the following java class and override addResourceHandlers() method like below:

    @Configuration
    class WebMVCCustomConfiguration implements WebMvcConfigurer {
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:static").resourceChain(true)
                .addResolver(new PathResourceResolver() {
                    @Override
                    protected Resource getResource(String resourcePath, Resource location) {
                        String path = "static/";
                        path += (resourcePath.contains(".") && !resourcePath.equals("index.html")) ? resourcePath : "index.html";
    
                        Resource resource = new ClassPathResource(path);
                        return resource.exists() ? resource : null;
                    }
                });
        }
      }
    

    This will fix all the issues and this solution does not exist anywhere.

提交回复
热议问题