[JS] Fetch ?

바보 개발자·2020년 9월 22일
0

JavaScript

목록 보기
6/12

fetch는 서버에 네트워크 요청을 보내고 정보를 받아올 수 있는 방법 중 하나.


기본문법

fetch(url)

Return Type: Promise

사용

 fetch("https://consolekakao.github.io")

 //url을 불러와서 성공시 promise형태로 성공시 resolve 실패시
//Uncaught (in promise) TypeError: Failed to fetch 같은 오류 출력


       .then( a => a.text())
       //.앞에서 resolve형식으로 작업 완료시 a에 이전 프로미스(fetch값)가 담김.
       //a.text 값 전달

       .then(t => console.log(t))
		//앞에서 a.text가 성공적으로 담기면 t에 a.text값이 담김.
		//콘솔에 t 출력.

fetch를 이용해 비동기로 안전하게 데이터 담아오기.


바로 코드로 보자.


<script>


            fetch("https://consolekakao.github.io")
            .then(response => response.text())
            .then(x => console.log(x))
            .catch(err => console.log(err));


    </script>

결과값:


<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>

      남이 하는걸 나도 할 수있게

    </title>
    <link rel="shortcut icon" type="image/x-icon"

    중략...

    <script src="/assets/js/main.js"></script>
  </body>
</html>


위와같이 안전하게 데이터를 모두 담아와서 출력할 수 있다.
profile
일단 해보자

0개의 댓글