본문 바로가기
[스파르타 코딩클럽]/비개발자를 위한, 웹개발 종합반

서버-클라이언트 통신(GET,POST)/JSON/Fetch연습

by 수민띠 2023. 2. 20.

서버 -> 클라이언트

JSON(JavaScript Object Notation)

서버에서 클라이언트로 데이터를 전달하는 방식

dictionary와 유사한 형태로 Key-Value로 이루어진 객체로 데이터를 내려준다

 

서울시 미세먼지 OpenAPI에 접속해서 확인해보기

 

http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99

 

출처: 스파르타코딩클럽<웹개발종합반>

클라이언트 -> 서버

클라이언트가 서버로 데이터를 요청할 때, 요청하는 데이터의 타입을 명시해야 한다.

HTTP는 GET과 POST 두가지 요청 타입을 제공하며, 요청하는 타입에 따라 다른 기능을 수행한다.

 

GET : 서버로부터 데이터를 가져오기 위한 요청. 주로 브라우저에서 링크를 클릭하거나 주소창에 URL을 입력하여 호출

데이터 조회(Read)  ex) 영화 목록 조회

 

POST : 서버에 데이터를 보내기 위한 요청. 보통 HTML form에서 입력한 정보를 서버로 전송할 때 사용

데이터 생성(Create), 변경(Update), 삭제(Delete) ex) 회원가입, 회원탈퇴, 비밀번호 수정

 

GET 방식으로 데이터를 전달하는 방법 (원하는 데이터를 가져오기 위한 데이터 전달)

URL 뒤에 물음표를 붙여 key=value로 전달

? 뒤부터 데이터 작성 시작점, & 데이터를 추가로 전달해야 한다는 의미

ex) google.com/search?q=아이폰&sourceid=chrome&ie=UTF-8

 위 주소는 google.com의 search 창구에 다음 정보를 전달
 q=아이폰               (검색어)
 sourceid=chrome        (브라우저 정보)
 ie=UTF-8               (인코딩 정보)

 

https://www.w3schools.com/jquery/jquery_get_started.asp

?가 없으면 데이터를 가져올 필요가 없는 창구.
이는 즉, 클라이언트가 데이터 요청 시 어떤 데이터든 제공된다는 의미

 


Fetch

Fetch(가지고 오다)란 자바스크립트에서 제공하는 API

이 API를 이용하면 서버로부터 데이터를 가져오거나, 서버로 데이터를 보낼 수 있다.

 

Fetch기본골격

fetch("여기에 URL을 입력").then(res => res.json()).then(data => {
    console.log(data)
})

코드 해석

fetch("URL") : 해당 URL로 웹 통신을 요청. 만약 괄호 안에 URL 이외의 값이 없다면, 기본적으로 GET 방식으로 요청

.then() : 통신 요청을 받은 다음 () 소괄호 안의 내용 실행

res ⇒ res.json() : 통신 요청을 받은 데이터는 JSON 형식으로 res 변수에 할당

.then(data ⇒ {}) : JSON 형태로 바뀐 데이터를 data 변수명으로 사용

 

Fetch통신의 결과 값 이용해보기

step1.미세먼지 데이터 위치 찾기 (객체 안의 RealtimeCityAir - row)

step2. 확인을 위해 console에서 검토

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
    fetch("http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99")
    .then(res => res.json())
    .then(data => {
      console.log(data['RealtimeCityAir']['row'][0])
    })
  </script>

step3. 반복문으로 구 데이터 출력해보기

  <script>
    fetch("http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99")
    .then(res => res.json())
    .then(data => {
      let rows = data['RealtimeCityAir']['row'] // 전체 구
      rows.forEach((a) =>{ //a: 구 데이터
        console.log(a);
      })
    })
  </script>

step4. 구 데이터에서 구 이름(MSRSTE_NM), 미세먼지 수치(IDEX_MVL)를 골라내 출력하기

  <script>
    fetch("http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99")
    .then(res => res.json())
    .then(data => {
      let rows = data['RealtimeCityAir']['row']
      rows.forEach((a) =>{
        console.log(a['MSRSTE_NM'], a['IDEX_MVL']);
      })
    })
  </script>
  
/* 변수를 사용하자
let gu_name = a['MSRSTE_NM']
let gu_mise = a['IDEX_MVL']
console.log(gu_name, gu_mise)
 */


Fetch 연습하기 (GET)

(좌)실행 전 (우)실행 후

<style type="text/css">
    div.question-box {
      margin: 10px 0 20px 0;
    }
    .bed {
      color : red;
    }
</style>

  <script>
 //q1이 실행되면
    function q1() {
 //데이터를 가져와서
      fetch("http://spartacodingclub.shop/sparta_api/seoulair")
      .then(res => res.json())
      .then(data => {
  // list만 추출하고
        let rows = data['RealtimeCityAir']['row'];
        $('#names-q1').empty() //버튼 누를때 빈 공간으로
  //list에서 필요한 정보를 추출하는 동안 조건문 적용
        rows.forEach((a) => {
          let gu_name = a['MSRSTE_NM']
          let gu_mise = a['IDEX_MVL']

          let temp_html = `` // 추가할 HTML요소
          
          if(gu_mise > 40){
            temp_html = `<li class="bed">${gu_name} : ${gu_mise}</li>`
          }else{
            temp_html = `<li>${gu_name} : ${gu_mise}</li>`
          }
          $('#names-q1').append(temp_html) //요소 추가
        })
      })
    }
  </script>