💚04_HTML5 & Javascript & CSS

#Front #비동기호출 #XMLHttpRequest #fetch #axios #jQuery.ajax #호출방법 #cors설정 #자격증명

roomname-dev 2024. 11. 19.
728x90
반응형

Front 페이지에서 비동기 호출하는 방법에 대해서 알아보겠습니다. 
XMLHttpRequest, fetch, axios, jQuery.ajax 이렇게 총 4가지에 대해서 먼저 알아보겠습니다. 
XMLHttpRequest와 fetch는 브라우저 내장 객체이며 axios는 라이브러리 jqeury.ajax는 jquery의 비동기 함수입니다. 


🦖일단 비동기 호출의 주용 특징으로는 

👉. 비동기적 : 요청을 보낸 후, 응답을 기다리는 동안 다른 작업을 계속할 수 있습니다. 
               이를 통해 사용자 경험을 향상시킬 수 있다.
               
👉. 서버와의 통신 : 서버에서 데이터를 받아와서 페이지에 동적으로 렌더링하거나, 폼 데이터를 
                   서버에 보내는 등 다양한 작업을 할 수 있음 
                   
👉. 페이지 새로 고침 없이 처리 : 웹 페이지를 새로 고침 없이 서버와 데이터를 주고받아 원활한 경험 제공

🦖withCredentials 설정 

👉. CORS(Cross-Origin Resource Sharing) 요청에서 자격증명을 포함할지 여부 설정 옵션 
클라이언트 측 HTTP옵션을 보낼때 쿠키, 인증헤더, TLS클라이언트 인증서와 같은 자격증명을 포함시킬지 결정 
👉. true : 요청에 자격증명(ex. 쿠키, HTTP인증헤더)을 포함
👉. false : 요청에 자격증명 미포함 (기본값은 false)

🎈XMLHttpRequest에서 withCredentials 적용 방법

XMLHttpRequest에서 withCredentials를 사용하면, 요청이 CORS 요청인 경우에도 쿠키와 같은 인증 정보를 
서버로 전송할 수 있습니다.

const xhr = new XMLHttpRequest(); 
xhr.open('GET', 'https://example.com/data', true); 
xhr.withCredentials = true; // 쿠키와 인증 정보를 함께 전송 
xhr.onreadystatechange = function() { 
    if (xhr.readyState === 4 && xhr.status === 200) { 
    console.log(xhr.responseText); 
    } 
}; 
xhr.send();

🎈fetch에서 withCredentials적용 방법

👉 fetch는 기본적으로 쿠키를 포함하지 않습니다. 그러나 credentials 옵션을 사용하여 
쿠키를 포함할 수 있습니다.
👉 credentials: 'same-origin': 동일 출처 요청에 대해서만 쿠키를 포함
👉 credentials: 'include': 다른 출처의 요청에도 쿠키를 포함

fetch('https://example.com/data', { 
method: 'GET', 
credentials: 'include' // 다른 출처의 요청에도 쿠키를 포함 
}
)
.then(response => response.json()) 
.then(data => console.log(data)) 
.catch(error => console.error('Error:', error));

🎈axios에서 withCredentials 적용 방법

👉 axios에서는 withCredentials 옵션을 설정하여 요청에 인증 정보를 포함시킬 수 있습니다. 
👉 기본적으로 axios는 withCredentials가 false로 설정되어 있습니다.

axios.get('https://example.com/data', { 
withCredentials: true // 쿠키와 인증 정보를 함께 전송 
}) 
.then(response => console.log(response.data)) 
.catch(error => console.error('Error:', error));

🎈jQuery.ajax에서 withCredentials 적용 방법

👉 jQuery.ajax에서는 xhrFields 옵션을 사용하여 withCredentials를 설정할 수 있습니다.

$.ajax({ 
    url: 'https://example.com/data', 
    method: 'GET', 
    xhrFields: { withCredentials: true // 쿠키와 인증 정보를 함께 전송 }, 
    success: function(data) {
    	console.log(data); 
	}, error: function(error) { 
        console.error('Error:', error); 
    } 
});

🦖withCredentials 유의사항

👉 서버설정 : CORS요청에서 인증 정보를 보내려면 서버 측에서도 해당 요청을 허용 해야함 

서버에서 Access-Control-Allow-Credentials 헤더를 true로 설정 필요 Access-Control-Allow-Origin은 *아니라 특정 출처

origin을 지정해야함 

Access-Control-Allow-Origin: https://your-frontend.com Access-Control-Allow-Credentials: true

👉 쿠키와 보안  : 사용시 쿠키에 민감한 정보가 담길수 있으므로 보안에 유의 필요 

Secure와 HttpOnly 플래그를 설정한 쿠키를 사용하여 보안 강화 필요 

728x90
반응형

댓글