1. axios 모듈 설치
2. CrossOrigin 설정 (CORS policy)
브라우저와 node.js에서 사용할 수 있는 Promise(비동기) 기반 HTTP 클라이언트 라이브러리
vue 프로젝트 디렉토리에 설치되어야함!
1) axiox 설치
cd [vue 프로젝트 디렉토리] //디렉토리 이동
yarn add axios //axios 설치
2)vue 파일 script에 import 하기
<script>
import axios from 'axios' //여기만 추가해주면 됨
//아래 코드는 예시 코드
export default {
name: 'HomeView',
methods: {
getData() {
//아래 스프링 서버 주소 (localhost:8080/)이 아닌 '/'그냥 슬래시만 쓰게 된다면
//스프링이 아니라 뷰 프로젝트 파일 index.html으로 불려간다.
axios.get('http://localhost:8080/')
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
}
}
}
</script>
프로젝트를 프론트와 백엔드로 나누고 난뒤 가장 골치였던 cors 정책...
CORS Policy 오류들은 같은 도메인 교차를 허용 안하기때문에 뜨는 오류라고 한다.
이를 허용해 주기위해 스프링에서 WebConfig
라는 클래스 파일을 만들고 아래와 같이 작성해 준다.
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import static org.springframework.http.CacheControl.maxAge;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://192.168.0.203:8081/", "http://localhost:8080") // Vue.js 애플리케이션의 주소
.allowedMethods("GET", "POST", "PUT", "DELETE") // 허용할 HTTP 메서드
.allowCredentials(true) // 자격 증명(예: 쿠키, 인증 헤더)을 허용할지 여부
.maxAge(3000);
}
}
@CrossOrigin(origins = "http://localhost:8081")
이 어노테이션을 컨트롤러에 달아서 설정할 수도 있지만 config 파일을 만들어 관리하는 것이 더욱 자세하게 설정할 수 있고 관리할 수 있다.
일부 컨트롤러에만 crossOrigin을 허용할 것이 아니라면 전역 config 파일을 사용하는 것을 추천한다.