Trying to have a REST API and a frontend app in the same project

47 views Asked by At

I have a Spring Boot app which has REST endpoints, but also a VueJS app (together with some Vue router logic). The problem is that whenever I hit, for instance, http://localhost:8080/information, I need to redirect to the HTML file with the VueJS logic. If the request URI starts with /api/v1, then I would like to hit the REST controllers.

I once accomplished this with a Spring Boot filter but now I can't remember how.

1

There are 1 answers

0
Agustn Ernesto Cardeilhac Bans On

Here how I implement it:

    @Component
    public class BackOfficeFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, 
    FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;

    String requestURI = req.getRequestURI();

    if(requestURI.contains("api")) {
        filterChain.doFilter(request, response);
        return;
    }

    if(requestURI.startsWith("/notfound")) {
        req.getRequestDispatcher("/").forward(request, response);
        return;
    }

    filterChain.doFilter(request, response);
   }
  }

If the request starts with "/api", then let it go and reach the rest controllers. If the reuqest starts with "/notfound" or any other vue route, forward to "/". This will make the browser to load the index html file but preserve the vue route. This will make the vue routing logic to enter into the scene. This could be a list as an application can have several routes. For any other request, continue and execute or let it go.