스프링 부트 + Vue.js 연동 같은 프로젝트 일 때 router 설정

728x90

스프링 부트 프로젝트에 vue.config.js 로 npm build 하여 /resources/static/ 경로에 index.html로 만들었을 경우

 

import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Login from "@/components/Login";

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

 

현재 vue 라우터는 / , /login 두 가지 뿐입니다.

 

여기서 /login으로 이동하면 Form이 하나가 있습니다. axios로 post를 이용해 /users 로 요청을 보내면

export default {
  name: "Login",
  methods:{
    submitForm(){
      const formData = new FormData()
      formData.append('email', this.email)
      formData.append('password', this.password)
      formData.append('name', this.name)
      this.axios.post('/users',formData).then(res => {
        console.log(res.data)
      })
    }
  }
}

 

해당 스프링 부트 컨트롤러에 의해 회원 가입 성공 메세지가 콘솔창에 출력되게 됩니다.

@RestController
@RequestMapping("/users")
public class UserController implements ErrorController {

@PostMapping
    public String postUser(@ModelAttribute User user){
        return "회원 가입 성공";
    }  
}

 

이 때, post 요청 후 새로 고침 처럼 깜박이고 다시 url이 그대로 남아있게 됩니다. 

여기서 http://localhost:8888/login 이라는 url로 직접 접속을 하게 되면 스프링 부트에 컨트롤러에 의해 url이 가로채지고 당연히 해당 컨트롤러가 없으니 404 에러가 나옵니다.

 

일단 vue 부터 수정하겠습니다.

export default {
  name: "Login",
  methods:{
    submitForm(){
      const formData = new FormData()
      formData.append('email', this.email)
      formData.append('password', this.password)
      formData.append('name', this.name)
      this.axios.post('/users',formData).then(res => {
        console.log(res.data)
        this.$router.push({path:'/'})
      })
    }
  }
}

콘솔에 회원 가입 성공 메세지가 뜨고 router.push 를 사용하여 '/' home path로 이동되게 하려고 합니다.

vue 프로젝트만 있을 경우에는 이렇게만 해도 성공적으로 동작하게 됩니다.

 

하지만 우리의 프로젝트는 스프링 부트와 뷰를 같은 프로젝트에서 사용 중이기에 

WebConfig 클래스를 만듭니다.

@Configuration
public class WebConfig 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) throws IOException {
                        Resource requestedResource = location.createRelative(resourcePath);
                        return requestedResource.exists() && requestedResource.isReadable() ? requestedResource
                                : new ClassPathResource("/static/index.html");
                    }
                });
    }
}

WebMvcConfigurer 를 상속받고, addResourceHandlers를 오버라이드 합니다.

요청을 /static/index.html 로 보내서 처리하겠다는 것으로 스프링 부트 프로젝트 위에 SPA의 프레임워크의 라우터 기능을 사용하기 위해서는 해당 작업이 필요합니다.

 

반응형