솔미는 성장중

[JS] fetch() 본문

JavaScript

[JS] fetch()

solming 2023. 7. 31. 18:06
728x90

fetch (주소, 옵션)

 

  • 네트워크를 통해 리소스의 요청(request)과 응답(response)을 처리한다
  • promise 인스턴스를 반환
console.log(fetch('https://www.omdbapi.com/?apikey=********&s=avengers'))
//Promise

 

📍  fetch를 통해 promise 인스턴스를 반환하니 뒤에 then 메소드를 써줄 수 있다.

fetch('https://www.omdbapi.com/?apikey=********&s=avengers'))
  .then(res => console.log(res))
//Response

📍  json 메소드를 호출해야 데이터를 꺼낼 수 있다.

fetch('https://www.omdbapi.com/?apikey=********&s=avengers'))
  .then(res => console.log(res))
//Response

📍  promise 인스턴스가 반환되는 것을 확인할 수 있다.

fetch('https://www.omdbapi.com/?apikey=********&s=avengers'))
  .then(res => console.log(res.json()))
//Promise

📍  반환된 Promise의 내용을 확인하기 위해서 한 번 더 then 메소드를 써준다.

fetch('https://www.omdbapi.com/?apikey=********&s=avengers'))
  .then(res => res.json())
  .then(json => console.log(json))
//Response:True
//Search: 검색한 결과들 (10개만 가져옴)
//totalResults: 숫자 (입력한 키워드로 찾을 수 있는 결과 개수)

 

📍  Await를 써서 표현한다면?

const wrap = async () => {
  const res = await fetch('https://www.omdbapi.com/?apikey=********&s=avengers')
  const json = await res.json()
  console.log(json)
}
wrap()
//위 코드블럭과 동일한 결과 출력

 

📍  옵션을 사용해보자!      method, headers, body

fetch('https://www.omdbapi.com/?apikey=********&s=avengers'),{
  method: 'GET' //어떤 값을 얻을 때 사용하는 메소드. 'POST', 'PUT', 'DELETE'도 가능.
  headers: {
    'Content-Type':'application/json'}, //서버로 전송되는 타입 지정
  body: JSON.stringify ({ //인수로 들어온 JS데이터를 모두 문자로 
  	name: 'solmi',
    age: 99,
    email: 'ovo10203@gmail.com'
  })
})
  .then(res => res.json())
  .then(json => console.log(json))

 

728x90