Vue.JS & Spring Boot - Redirect to homepage on 404 Vue.JS & Spring Boot - Redirect to homepage on 404 vue.js vue.js

Vue.JS & Spring Boot - Redirect to homepage on 404


Solved with the following code:

@Controllerpublic class RoutesController implements ErrorController {    private static final String PATH = "/error";    @RequestMapping(value = PATH)    public String error() {        return "forward:/";    }    @Override    public String getErrorPath() {        return PATH;    }}


What's happening in your case is that Spring boot is taking the requests and, because nothing is mapped to the URL is giving you a 404. What you want to happen instead is to allow your Vue.js app to handle the unmapped URL's (IE, redirect any unmapped URL's to your index.html).

The first thing you need to do is adding this to your routes configuration in your router:

export default new Router({    mode: 'history',    routes: [{        path: '/',        name: 'home',        component: Home    },    {        path: '/result',        name: 'result',        component: Result,        props: true    },    {        path: '/result/:userid',        name: 'autoResult',        component: Result,        props: true    },    {        path: '*',        component: NotFound    }  ]})

Here we added an extra route as the last path (because routes are matched sequentially) that renders a component.

After that, you need to make Spring boot redirect every unmatched request to index.html, in order to do that, you want spring to throw an exception when it finds and unmapped route and in the handler of the exception redirect to your index.html.

First, add this line to your application.properties:

spring.mvc.throw-exception-if-no-handler-found=true

And add a ControllerAdvice to handle the thrown Exception, like this:

//In some controller or inside a @ControllerAdvice annotated class@ExceptionHandler(NoHandlerFoundException.class)String noHandlerFound(NoHandlerFoundException ex){    return "classpath:index.html";}

Here you can find a little bit more info on making Spring boot redirect unmapped requests to your index.html


Unfortunately none of the above answers worked for me, luckily I've found this answer in another thread:https://stackoverflow.com/a/59290035/1254782

It is simple and short and works like a charm for my use case, which might slightly differ from the original question, but I think it is quite similar. It might be useful for someone looking for serving vuejs SPA from spring boot backend.