다른 사이트 간의 통신을 방지하는 CORS 해결 방법

1. 서로 다른 사이트 간의 통신(가져오기)

mms와 imsapi/smsapi 간의 통신

– mms의 index.jsp에 커뮤니케이션 버튼을 생성하고 버튼의 onclick 이벤트 기능을 정의한다.

1-1) 임사피의 모든 아이템 받기

<index.jsp>
=================================================================
<body>

<button onclick="getItemAll()">imsapi의 모든 item 가져오기</button>

<script type="text/javascript">

function getItemAll(){

		// fetch통신을 위한 url 설정
      let url = "http://localhost:9001/item/all"; //imsapi 서버의 item 전부를 조회하는  url
      // fetch 통신을 위한 옵션 설정
      let options = { 
            method : "GET", // 데이터를 조회하므로 GET
            headers : {"Content-Type" : "application/json"
               }
      }
      
      fetch(url, options) //fetch 통신 시작
      .then(res =>{ // fetch 통신 결과를 response로 받음. res는 reponse의 약자임.
         if(!res.ok){ // fetch 통신 결과가 ok가 아니면 실패했다는 의미임.
            alert("실패");
            throw new Error("에러 발생");
         }
         return res.json(); // fetch 통신 결과가 ok이면, 넘겨받은 데이터를 json으로 변환시킴
      })
      .then(data => {
    	  alert("조회 성공")
         console.log(data.list);
      })
      .catch(error=>{  // 통신 자체가 안 되었거나, 통신이 성공한 후에 추가작업에 문제가 있을 때 호출됨.
         alert(111)
         console.log(error);
      })
   }
   
</script>

</body>

1-2) smsapi에 하나의 직원 데이터 추가

<index.jsp>
==========================================================================
<body>

<button onclick="insertAStaff()">smsapi에 staff 데이터 1개 추가하기</button>

<script type="text/javascript">

function insertAStaff(){
		let url = "http://localhost:9002/staff";
		let options = { 
	    	method : "POST",
	    	headers : {
	    		"Content-Type" : "application/json"
	    		}
	    }
		
		if(options.method !=="GET"){ 
			options.body = JSON.stringify({ // 추가할 데이터의 정보
				username : "m017",
				password : "1",
				password2 : "1"
			})
		}
		
		fetch(url, options)
	      .then(res =>{
	         if(!res.ok){
	            alert("입력 실패");
	            throw new Error("입력 실패로 에러 발생");
	         }
	         return res.json();
	      })
	      .then(data => {
	    	 alert("입력 성공");
	         console.log(data);
	      })
	      .catch(error=>{
	         alert(111)
	         console.log(error.message);
	      })
		
	}
    
</script>

</body>

1-3) 사용자 이름이 m017인 smsapi 직원의 비밀번호를 변경합니다.

<index.jsp>
==========================================================================
<body>

<button onclick="updatePwStaff()">smsapi의 staff 중 username이 m017인 데이터의 비번 변경</button>

<script type="text/javascript">

	function updatePwStaff(){
		let url = "http://localhost:9002/staff";
		let options = { 
	    	method : "PUT",
	    	headers : {
	    		"Content-Type" : "application/json"
	    		}
	    }
		
		if(options.method !=="GET"){
			options.body = JSON.stringify({ // 수정할 정보 내용
				username : "m017",
				orgPassword : "2",
				password : "0",
				password2 : "0"
			})
		}
		
		fetch(url, options)
	      .then(res =>{
	         if(!res.ok){
	            alert("수정 실패");
	            throw new Error("수정 실패로 에러 발생");
	         }
	         return res.json();
	      })
	      .then(data => {
	    	 alert("수정 성공");
	         console.log(data);
	      })
	      .catch(error=>{
	         alert(111)
	         console.log(error.message);
	      })
	}
       
</script>

</body>

2. 1번 상태에서 버튼을 누르면 CORS 에러가 발생합니다.

이를 해결하기 위해 WebMvcConfigurer를 상속받은 WebMvcConfigurer 클래스를 생성하고 서비스 요청을 받은 imsapi, smsapi 서버에 다음을 추가한다.

@Configuration
public class WebMvcConfiguerImpl implements WebMvcConfigurer {

	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**")
		.allowedOrigins("http://localhost:9000")
		.allowedMethods("GET", "POST", "PUT", "DELETE")
		.allowedHeaders("*")
		.allowCredentials(true) //인증정보 허용
		.maxAge(3600); //초 단위고 3600초 1시간동안 열어두겠다는 뜻
	}
}