본문 바로가기

Front/Java Script

fetch().then()

/* openweathermap api로 날씨를 가져오기 */

const latitude = ' ';
const longitude = ' ';
const API_KEY = '  ';

fetch(
  `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`
)
.then(function(response){
	   	console.log(response);
});

 

 

console.log(response) 결과

response에 있는 body는 보이지 않음.

이 body는 스트림이고, 데이터가 완전히 다 받아진 상태가 아님.

 

 

 

/* .json() 함수 사용 */

fetch(
  `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`
)
.then(function(response){
	   	return response.json();		// Promise 반환
})
.then(function(json){
	   	console.log(json);
});

 

.json()은 Response 스트림을 가져와 스트림이 완료될 때까지 읽고,

다 읽은 body의 텍스트를 Promise 형태로 반환한다.

 

 

p.s. axios를 사용할 경우, .json() 단계를 넘어가도 된다.

     axios는 json()과정을 자동으로 해주는 셈이다.

 

[추가 공부할 내용]

Priomise, axios