[vue/spring] axios로 프론트와 백엔드 연결하기

단코딩·2024년 5월 17일
0

1. axios 모듈 설치

2. CrossOrigin 설정 (CORS policy)

0. axios 란?

브라우저와 node.js에서 사용할 수 있는 Promise(비동기) 기반 HTTP 클라이언트 라이브러리

  • 브라우저를 위해 XMLHttpRequests 생성
  • node.js를 위해 http 요청 생성
  • Promise API를 지원 (비동기 작업을 지원한다는 말)
  • 요청 및 응답 인터셉트
  • 요청 및 응답 데이터 변환
  • 요청 취소
  • JSON 데이터 자동 변환
  • XSRF를 막기위한 클라이언트 사이드 지원

1. axios 모듈 설치

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>

2. CrossOrigin 설정 (CORS policy)

프로젝트를 프론트와 백엔드로 나누고 난뒤 가장 골치였던 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 파일을 사용하는 것을 추천한다.

profile
내가 바란 건 한 개 뿐이야

0개의 댓글