Angular routing doesn't work after deploy into a Springboot Application
Asked Answered
M

2

7

I have build a Springboot Application including Angluar5. I have a gradle build script which loads the angular files into my springboot project.The files are under resources/static of my springboot project. When i start my application the routing of angular is not working anymore and i get

Error: Cannot match any routes. URL Segment: 'access'

My project structure:

enter image description here

I deployed my angular app with following statement:

ng build --deploy-url=BeatAcknowledgeTest --op=../backend/src/main/resources/static

This will make my static files accessable to following link:

www.mySite.com/BeatAcknowledgeTest/...

If i type

www.mySite.com/BeatAcknowledgeTest/access

the pages renders and all is good but when i am in another component, for example

www.mySite.com/BeatAcknowledgeTest/home

and i click on a button which routes me to

www.mySite.com/BeatAcknowledgeTest/access

i am getting an error and my application is not redirecting.

Any suggestions?

Marris answered 24/4, 2018 at 12:7 Comment(2)
Possible duplicate of Springboot/Angular2 - How to handle HTML5 urls?Bays
This is due to the push state requiring your server to serve your Angular application for every route. It's commonly asked, as you can see in the duplicate reference, and also #24838215.Bays
K
7

I solved this issue by creating RequestForwardingController in my app. Which will take care of all the routing:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RequestForwardingController {
    @RequestMapping(value = "/**/{[path:[^\\.]*}")
    public String redirect() {
        // Forward to home page so that angular routing is preserved.
        return "forward:/";
    }
}

It also solves the reload URL issue as well. In which you click on reload button of browser it will show Spring boot error page.

Kilocycle answered 12/12, 2018 at 10:47 Comment(1)
Shouldn't the RequestMapping's value be "/**/{path:[^\\.]*}" instead (without the first [ ?Claypool
J
1

One of the ways to fix this is customizing the MVC configuration, which is illustrated by this article based on this answer: https://stackoverflow.com/a/46854105

Jacques answered 1/2, 2021 at 6:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.