본문 바로가기
vue

[vue] 스프링(spring)에서 vue router 사용법

by devjh 2021. 11. 2.
반응형

spring과 vue 프로젝트를 연동한 후 vue router의 위치를 브라우저의 검색창에 입력하면

404 에러를 떨어뜨려줍니다. (spring컨트롤러는 요청한 url 에 대한 정보가 없습니다)

modelAndView가 떠오릅니다.

controller에 modelAndView를 사용해서 html을 떨어뜨리려고보니

spa 프레임 워크인 vue는 빌드된 html이 하나뿐입니다.

 

아래의 방법으로 해결 합니다.

 

1. vue.config.js

// vue.config.js
const path = require("path");
module.exports = {
  outputDir: path.resolve(__dirname, "../src/main/resources/static"),
  indexPath: path.resolve(__dirname, "../src/main/resources/static/index.html"),
}

vue를 빌드 결과물을 spring의 src/main/resources/static에 다 넣어줍니다.

 

2. WebConfig.java

@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");
                    }
                });
    }
}


먼저 @Controller, @RestController를 찾아본후 매핑되는 url이 없는경우 index.html을 내려주어 vue-router를 이용할 수 있게 해줍니다.

반응형

댓글