투케이2K

38. (Http/fetch) fetch (페치) Web API 사용해 GET 방식 이미지 주소 호출 및 response blob 블랍 데이터 확인 본문

Http & Api

38. (Http/fetch) fetch (페치) Web API 사용해 GET 방식 이미지 주소 호출 및 response blob 블랍 데이터 확인

투케이2K 2022. 12. 13. 09:55
반응형

[개발 환경 설정]

개발 툴 : Edit++

개발 기술 : fetch

 

[소스 코드]

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

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

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





        // [http 요청 수행 메소드 정의]
        async function httpReq(){
            console.log("");
            console.log("=========================================");
            console.log("[httpReq] : [HTTP 요청 실시]");
            console.log("=========================================");
            console.log("");

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

            // [http 요청 주소 정의 실시]
            var urlData = "https://s3-ap-southeast-1.amazonaws.com/tksproduction/bmtimages/pY3BnhPQYpTxasKfx.jpeg";

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

            // [응답 데이터를 담기 위한 변수 선언]
            var responseHeader = new Object(); // header

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

            // [fetch http 요청 실시]
            const result = await fetch(urlData, {
                method: "GET",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                cache: 'no-cache',
                body: null,
            });


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

            // [response 확인]
            const status = await result.status;
            const type = await result.type;
            const url = await result.url;
            await result.headers.forEach(function(value, name) {
                responseHeader[String(name)] = String(value); 
            });
            await result.blob().then(imageBlob => { // [파일 blob 형태]

                // [createObjectURL 생성]
                const imageObjectURL = URL.createObjectURL(imageBlob);


                // [동적 이미지 생성 및 body 에 추가 실시]
                const image = document.createElement('img');
                image.src = imageObjectURL;
        
                const container = document.body;
                container.append(image);
            });

            console.log("");
            console.log("=========================================");
            console.log("[httpReq] : [HTTP 응답 확인]");
            console.log("[status] : " + status);
            console.log("[type] : " + type);
            console.log("[url] : " + url);
            console.log("[responseHeader] : " + JSON.stringify(responseHeader));
            console.log("=========================================");
            console.log("");

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

        };

    </script>
 

[결과 출력]


반응형
Comments