[Node.js] fetch()
2022.11.24
💡 오늘의 JavaScript 공부
▶️ fetch API
우리가 주로 사용하는 사이트들은 시시각각 변하는 정보들과 늘 고정적인 정보들이 따로 분리되어 있는 것을 확인할 수 있다. 이중에서 날씨, 증시, 최신 뉴스등이 바로 동적으로 데이터를 받아야 하는 정보이다.
많은 웹사이트들에서는 해당 정보만 업데이트하기 위해 요청 API를 이용한다. 그중 대표적인 fetchAPI를 공부해보았다.
📌 fetch API 기본구조
let url =
"https://koreanjson.com/posts/1";
fetch(url)
.then((response) => response.json())
.then((json) => console.log(json))
.catch((error) => console.log(error));
어제와 마찬가지로 요청의 결과를 하나의 객체로 합치는 것
🕹basicChaining.js
const { response } = require('express');
const newsURL = 'http://localhost:4999/data/latestNews';
const weatherURL = 'http://localhost:4999/data/weather';
function getNewsAndWeather() {
// TODO: fetch을 이용해 작성합니다
// TODO: 여러개의 Promise를 then으로 연결하여 작성합니다
return fetch(newsURL) // newsURL 받아와서
.then((response) => response.json()) // JSON 형태로 변환시킴
.then((json1) => { // 그 결과를 json1에 담았고
return fetch(weatherURL) // weatherURL을 가져와서
.then((response) => response.json()) // JSON 형태로 변환시킴
.then((json2) => { // 그 결과를 json2에 담았고
return {
news: json1.data,
weather : json2
} // 객체로 합침
})
})
}
분명 무언가 잘못되었다고 하더라도 하나도 통과되지 않을리가 없는데 계속해서 오류가 발생했다.
이유를 계속해서 찾지 못하고 열만 받아 있다가 함께 코드를 짰던 페어님이 선언된 newsURL, weatherURL말고 fetch에 바로 주소를 입력해보라고 하셨다.
그 결과
🕹basicChaining.js
function getNewsAndWeather() {
// TODO: fetch을 이용해 작성합니다
// TODO: 여러개의 Promise를 then으로 연결하여 작성합니다
return fetch('http://localhost:4999/data/latestNews') // newsURL 받아와서
.then((response) => response.json()) // JSON 형태로 변환시킴
.then((json1) => { // 그 결과를 json1에 담았고
return fetch('http://localhost:4999/data/weather') // weatherURL을 가져와서
.then((response) => response.json()) // JSON 형태로 변환시킴
.then((json2) => { // 그 결과를 json2에 담았고
return {
news: json1.data,
weather : json2
} // 객체로 합침
})
})
}
하… 뭐가 문제인지 모르겠지만 … 주소를 제대로 읽어오지 못했던 것 같ㄷㅏ… 우선 해결했으니 다음문제
🕹PromiseAll.js
1차 코드
function getNewsAndWeatherAll() {
return Promise.all([fetch('http://localhost:4999/data/latestNews'), fetch('http://localhost:4999/data/weather')]) // 두 url 모두에 fetch를 적용한다.
.then([newsReponse, weatherResponse]) => { // fetch한 결과를 각각 newsResponse, weatherReponse라고 하고
return Promise.all([newsReponse.json(), weatherResponse.json()]); // 응답을 json형태로 변환시킨다.
})
.then(([json1, json2]) => { // 그 결과를 각각 json1, json2라고 할 때
return { // 다음과 같은 객체로 리턴한다.
news : json1.data,
weather : json2
}
})
}
짜놓고 내가 보기에도 조금 지저분한 부분이 많고 코드가 깔끔하지 않아서 다른 구조로 깔끔하게 짜보았다. 나름..
2차 코드
function getNewsAndWeatherAll() {
// TODO: Promise.all을 이용해 작성합니다
// 1단계 : Promise.all로 fetch 데이터 받아오기
// 2단계 : json으로 변환하기
return Promise.all([
fetch('http://localhost:4999/data/latestNews') // 1단계
.then(response => response.json()), // 2단계
fetch('http://localhost:4999/data/weather') // 1단계
.then(response => response.json()) // 2단계
])
.then((values) => { // 현재 values에는 배열의 형태로 newsURL과 weatherURL이 병렬로 담겨있음
return { // 그래서 index를 활용해서 사용
news: values[0].data,
weather: values[1]
}
})
}
🕹asyncAwait.js
async function getNewsAndWeatherAsync() {
// TODO: async/await 키워드를 이용해 작성합니다
const news = await fetch('http://localhost:4999/data/latestNews')
.then((response) => response.json())
const weather = await fetch('http://localhost:4999/data/weather')
.then((response) => response.json())
return {news: news.data , weather: weather}
}
결말은 매우 개운하고 행복했다… ㅎ
페어분 말씀으로는 다시 과제 파일을 삭제하고 새롭게 git clone 해서 같은 코드 입력하면 newsURL, weatherURL이 불러와지지 않는 오류가 해결된다고 하셨다 😇
[ 한국 vs 우루과이 ] 월드컵 하는 날
👏🏻👏🏻👏🏻👏🏻👏🏻👏🏻 한국 화이팅 👏🏻👏🏻👏🏻👏🏻👏🏻👏🏻
Comments