Fetch

김나영·2023년 6월 5일

웹개발 종합반

목록 보기
5/6
post-thumbnail

Fetch

  • 서버에서 데이터를 가져와서 활용할 수 있는 방법
<!doctype html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Fetch 시작하기</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
		<script>
		</script>
</head>
<body>
    Fetch 연습을 위한 페이지
</body>
</html>
  • script 사이에 fetch가 들어감
fetch("여기에 URL을 입력").then(res => res.json()).then(data => {
		console.log(data)
})
  • fetch의 기본 골격
  • fetch("여기에 URL을 입력")
    : 이 URL로 웹 통신을 요청. 괄호 안에 다른 것이 없다면 GET!
  • .then(res => res.json())
    : 통신 요청을 받은 데이터는 res라는 이름으로 JSON화 함
  • .then(data => {
    console.log(data)=> 개발자 도구에 찍어보기
    })
    : JSON 형태로 바뀐 데이터를 data라는 이름으로 붙여 사용
<!doctype html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Fetch 시작하기</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        fetch("여기에 URL을 입력").then(res => res.json()).then(data => {
            console.log(data)
        })
    </script>
</head>
<body>
    Fetch 연습을 위한 페이지
</body>
</html>
  • Fetch 코드
    • fetch("여기에 URL을 입력") ← 이 URL로 웹 통신 요청을 보낼 거야!
      • ← 이 괄호 안에 URL밖에 들어있지 않다면 기본상태인 GET!
    • .then() ← 통신 요청을 받은 다음 이렇게 할 거야!
    • res ⇒ res.json()
      • ← 통신 요청을 받은 데이터는 res 라는 이름을 붙일 거야(변경 가능)
      • ← res는 JSON 형태로 바꿔서 조작할 수 있게 할 거야!
    • .then(data ⇒ {}) ←JSON 형태로 바뀐 데이터를 data 라는 이름으로 붙일거야

미세먼지 데이터 출력

fetch("http://spartacodingclub.shop/sparta_api/seoulair")
	.then(res => res.json()) 
	.then(data => { 
		console.log(data['RealtimeCityAir']['row'][0]);
	})
  • fetch("미세먼지 URL 삽입")
  • RealtimeCityAir의 row에 미세먼지 데이터가 들어가 있는 것을 확인
fetch("http://spartacodingclub.shop/sparta_api/seoulair") // 기본 요청(GET)
	.then(res => res.json()) // 요청해서 받은 데이터를 JSON화
	.then(data => { // JSON화 한 데이터를 다시 data로 이름짓기
		let rows = data['RealtimeCityAir']['row']
		rows.forEach((a) => {
			console.log(a) // 미세먼지 데이터 리스트의 길이만큼 반복해서 하나씩 개발자 도구에서 보기
		})
	})
  • row의 값을 rows에 담기
  • 반복문 이용
fetch("http://spartacodingclub.shop/sparta_api/seoulair") // 기본 요청(GET)
	.then(res => res.json()) // 요청해서 받은 데이터를 JSON화
	.then(data => { // JSON화 한 데이터를 다시 data로 이름짓기
		let rows = data['RealtimeCityAir']['row']
		rows.forEach((a) => {
			console.log(a['MSRSTE_NM'], a['IDEX_MVL'])
            // 미세먼지 데이터 리스트의 길이만큼 반복해서 하나씩 개발자 도구에서 보기
			// 구의 이름, 미세먼지 수치 값을 개발자 도구에서 찍어보기
		})
	})
  • 이름 키 값인 "MSRSTE_NM", 미세먼지 수치 키값인 "IDEX_MVL" 출력
fetch("http://spartacodingclub.shop/sparta_api/seoulair").then(res => res.json()).then(data => { 
		let rows = data['RealtimeCityAir']['row']
		rows.forEach((a) => {
			console.log(a['MSRSTE_NM'], a['IDEX_MVL'])
		})
	})
  • 결과

0개의 댓글