Notice
Recent Posts
Recent Comments
Link
솔미는 성장중
[JS] fetch() 본문
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
'JavaScript' 카테고리의 다른 글
[JS] 불변성 (0) | 2023.07.31 |
---|---|
[JS] DOM (0) | 2023.07.31 |
[JS] 동기/비동기 (콜백 패턴, promise, Async & Await, Resolve, Reject, 에러 핸들링, 반복문에서의 비동기) (0) | 2023.07.31 |
[JS] 모듈 (0) | 2023.07.23 |
[JS] prototype + 배열 만드는 방법 (1) | 2023.07.19 |