투케이2K

39. (Http/fetch) fetch (페치) Web API 사용해 http 요청 수행 및 콜백 (callback) 응답 확인 실시 본문

Http & Api

39. (Http/fetch) fetch (페치) Web API 사용해 http 요청 수행 및 콜백 (callback) 응답 확인 실시

투케이2K 2022. 12. 16. 00:23
반응형

[개발 환경 설정]

개발 툴 : Edit++

개발 기술 : fetch

 

[소스 코드]

	<!-- [내부 자바스크립트 J쿼리 이벤트 지정] -->
	<script>
    	

        /*
        -----------------------------------------
        [요약 설명]
        -----------------------------------------
        1. window.onload : 웹페이지 로드 완료 상태를 확인합니다
        -----------------------------------------
        2. fetch 함수는 XMLHttpRequest 객체보다 최신화 된 HTTP 요청 및 응답 기능을 제공하는 Web API 입니다
        -----------------------------------------
        3. fetch 함수는 별도의 라이브러리 설치 필요 없이 브라우저에 함수가 내장 되어있어 간편히 HTTP 요청을 수행할 수 있습니다​
        -----------------------------------------
        4. 로직 : 비동기 방식 http 요청 >> 콜백 응답 확인 수행
        -----------------------------------------
        */





    	// [html 최초 로드 및 이벤트 상시 대기 실시] 
        window.onload = function() {
            console.log("");
            console.log("=========================================");
            console.log("[window onload] : [start]");
            console.log("=========================================");
            console.log(""); 


            // [테스트 함수 호출]
            testMain();
        };





        // [자바스크립트 테스트 코드]
        function testMain(){
        	console.log("");
            console.log("=========================================");
            console.log("[testMain] : [start]");
            console.log("=========================================");
            console.log("");


            // -----------------------------------

            // [httpReq 메소드 호출 및 콜백 응답 확인]
            httpReq(function(success, response){
                console.log("");
                console.log("=========================================");
                console.log("[testMain] : [CALLBACK]");
                console.log("[success] : " + success);
                console.log("[response] : " + JSON.stringify(response));
                console.log("=========================================");
                console.log("");
            });


            // -----------------------------------
                                                
        };





        // [http 요청 수행 메소드 정의]
        function httpReq(callback){

            // -----------------------------------

            // [http 요청 주소 정의 실시]
            var urlData = "https://jsonplaceholder.typicode.com/posts?userId=1&id=1";

            // -----------------------------------

            // [fetch http 요청 실시]
            fetch(urlData, {
                method: "GET", // 전송 방식
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded", // 헤더 설정
                },
                cache: 'no-cache', // 캐시 설정
                body: null,
            })
            .then((response) => response.json())
            .then((data) => {

                // [콜백 반환]
                callback(true, data)
            })
            .catch((error) => {

                // [콜백 반환]
                callback(false, error)
            });

            // -----------------------------------

        };


    </script>
 

[결과 출력]


 
반응형
Comments