fetch사용시 유의 사항 (json() 함수 사용 <= 이건뭐냐고요? response.json() 프로미스객체서 사용), 과제 다시 풀어보기
비동기식 데이터를 가져오는 방식인 Ajax의 한 방법인 fetch
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Using Fetch - Web APIs | MDN
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across th
developer.mozilla.org
fetch를 사용하다보면 response.json()을 계속 사용하게된다.
JSON.parse와 stringtify()만 배웠는데 이함수이 사용법에대해서 공부해보자.
fetch의 짝궁 json()
fetch는 기본적으로 js에서 제공하는 함수다.
이 fetch를 사용할경우? 응답받은 response를 직접 변환해줘야한다.
즉. fetch로는 데이터를 바로 사용 할 수 없다.
fetch를 사용할 땐 두 단계를 거쳐야 한다.
1. 먼저 올바른 url로 요청을 보낸다
2. 바로 뒤에오는 응답에 대해 json()을 해준다. => json()은 프로미스 객체에서!!!
"Note that despite the method being named json(), the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object."
https://developer.mozilla.org/en-US/docs/Web/API/Response/json
Response.json() - Web APIs | MDN
The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON.
developer.mozilla.org
예시를 통해 알아보자

let url =
"https://v1.nocodeapi.com/codestates/google_sheets/YbFMAAgOPgIwEXUU?tabId=최신뉴스";
위의 url을 사용하기전, url을 검색해보자
객체안의 데이타들이 모두 json화 되어있는것을 볼수있다.
let url =
"https://v1.nocodeapi.com/codestates/google_sheets/YbFMAAgOPgIwEXUU?tabId=최신뉴스";
fetch(url)
.then((response) => response.json())
.then((json) => console.log(json))
.catch((error) => console.log(error));
크롬창에 위와같이 입력한 후 콘솔로그를 통해서 json()시킨 데이터를 찍어보면?
response를 response.json()한 전부가져온다.

fetch로 받아온 값은 결국 자바스크립트의 일반 객체가 아니고 제이슨화 시켜져 있는 데이터이기에
그것을 .json()으로 다시 풀어주는 작업이 필요한것.
json.data를 검색해서
data값만을 가져올수도 있다!
이제 과제를 위한 모든 이론과 개념을 숙지했다.
다시한번 혼자 풀어보자.

서버에서 받아온 데이터를 확인하자.
어떤 모습을 하고있는지 알아야 잘써먹을 수있으니 꼭 확인할것.
var newsURL = 'http://localhost:5000/data/latestNews';
var weatherURL = 'http://localhost:5000/data/weather';
function getNewsAndWeather() {
// TODO: fetch을 이용해 작성합니다
// TODO: 여러개의 Promise를 then으로 연결하여 작성합니다
return fetch(newsURL)
.then((newsData)=>newsData.json()) //newsData는 fetch로 가져온 데이터로 그냥 변수 내가 만든이름, 짝궁인 제이슨화시키기
.then((newsData)=>{ //그냥 내비두면안되고 다시 데이터를 가져와야됨
return fetch(weatherURL) //리턴을 하면 다른 데이터로 이동한다고 생각해도된다. 그다음 작업으로가는것
.then((weaData)=>weaData.json()) //위와동일
.then((weaData)=>{
return {news: newsData.data,weather: weaData}; //마지막 리턴은 {}<-객체. 가져올정보들
})
})
}
getNewsAndWeather().then(data => console.log(data))
if (typeof window === 'undefined') {
module.exports = {
getNewsAndWeather
}
}
첫시도에서 newsData.dat를 안썼으나 오류가 발생
테스트에서 요구하는것이 무엇인지를 살펴보니. 객체가 나와야한다. 그럼 나와야하는 객체의 모양을 살펴보니...
news부분에는 배열을 담고있다. 즉 . news.data를 원하는것이다. key값도 확인하여 직접 넣어주자.
02_promiseAll
var newsURL = 'http://localhost:5000/data/latestNews';
var weatherURL = 'http://localhost:5000/data/weather';
function getNewsAndWeatherAll() {
// TODO: Promise.all을 이용해 작성합니다
let user1 = fetch(newsURL).then(data => data.json())
let user2 = fetch(weatherURL).then(data => data.json())
return Promise.all([user1,user2]).then((value)=>{
return {news : value[0].data , weather : value[1]}
})
}
if (typeof window === 'undefined') {
module.exports = {
getNewsAndWeatherAll
}
}
주의해야할점은 value받은것이 배열안에 들어가있으니 리턴할때는 key는 위와 같이 {news : ?? , weather : ?? } 이 되야하며, 밸류는 value[0].data, value[1] 을 해줘야한다.
03_asyncAwait
var newsURL = 'http://localhost:5000/data/latestNews';
var weatherURL = 'http://localhost:5000/data/weather';
async function getNewsAndWeatherAsync() {
//return JSON.parse(`[${await getDataFromFilePromise(user1Path)}, ${await getDataFromFilePromise(user2Path)}]`)
// TODO: async/await 키워드를 이용해 작성합니다
const news1 = await fetch(newsURL).then((newsData)=>newsData.json())
const weather1 = await fetch(weatherURL).then((weatherData)=>weatherData.json())
return {news : news1.data, weather : weather1 }
}
if (typeof window === 'undefined') {
module.exports = {
getNewsAndWeatherAsync
}
}