투케이2K

58. (Http/fetch) fetch (페치) Web API 사용해 http patch 방식 요청 수행 및 응답 확인 본문

Http & Api

58. (Http/fetch) fetch (페치) Web API 사용해 http patch 방식 요청 수행 및 응답 확인

투케이2K 2023. 7. 13. 20:38
반응형

[개발 환경 설정]

개발 툴 : Edit++

개발 기술 : fetch

 

[소스 코드]

<!DOCTYPE HTML>
<html lang="ko">
<head>
	<title>javaScriptTest</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">

    <!-- 내부 CSS 스타일 지정 -->
    <style>
    </style>




    <!-- [CDN 설정 실시] -->





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

        /*
        -----------------------------------------
        [요약 설명]
        -----------------------------------------
        1. window.onload : 웹페이지 로드 완료 상태를 확인합니다
        -----------------------------------------
        2. fetch 함수는 XMLHttpRequest 객체보다 최신화 된 HTTP 요청 및 응답 기능을 제공하는 Web API 입니다
        -----------------------------------------
        3. fetch 함수는 별도의 라이브러리 설치 필요 없이 브라우저에 함수가 내장 되어있어 간편히 HTTP 요청을 수행할 수 있습니다​
        -----------------------------------------
        4. PATCH 메소드는 리소스의 부분적인 수정을 할 때에 사용됩니다
        -----------------------------------------
        5. PATCH 메소드는 PUT 메소드와 달리 멱등성을 가지지 않는데, 이는 동일한 patch 요청이 다른 결과를 야기할 수도 있음을 뜻합니다
        -----------------------------------------
        */





    	// [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("-----------------------------------------");
                console.log("[success] : " + success);
                console.log("-----------------------------------------");
                console.log("[response] : " + JSON.stringify(response));
                console.log("=========================================");
                console.log("");
            });


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





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

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

            // [http 요청 주소 정의 실시]
            var REQ_URL = "http://jsonplaceholder.typicode.com/posts/1";

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

            // [http 요청 데이터 정의 실시]
            var REQ_PARAM = {
                title: 'foo'
            };

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

            // [fetch http 요청 실시]
            fetch(REQ_URL, {
                method: "PATCH",
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                },
                cache: 'no-cache',
                body: JSON.stringify(REQ_PARAM),
            })
            .then((response) => response.json())
            .then((data) => {

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

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

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

        };

    </script>

</head>


<body>

</body>


</html>
 

[결과 출력]

 

=========================================
[testMain] : [CALLBACK]
-----------------------------------------
[success] : true
-----------------------------------------
[response] : {"userId":1,"id":1,"title":"foo","body":"quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}
=========================================

 

반응형
Comments