const getDadJoke = async () => {
const config = { headers: { Accept: 'application/json' } }
const res = await axios.get('https://icanhazdadjoke.com/', config)
console.log(res);
}
해당 icanhazdadjoke api는 json으로 받기 위해선 accecpt headers가 필요하기때문에 config 변수로 해당 값을 넣었다.
https://icanhazdadjoke.com/api
icanhazdadjoke
icanhazdadjoke.com
const getDadJoke = async () => {
const config = { headers: { Accept: 'application/json' } }
const res = await axios.get('https://icanhazdadjoke.com/', config)
console.log(res.data.joke);
}
//출력값 Why is the ocean always blue? Because the shore never waves back. (각종개그)
console.log의 부분을 res.data.joke로 하면 해당 api의 data에 있는 joke를 가져와 출력함.
header를 이용한 joke api 버튼 구현
const jokes = document.querySelector('#jokes'); // joke ul 선택
const getDadJoke = async () => {
try {
const config = { headers: { Accept: 'application/json' } }
const res = await axios.get('https://icanhazdadjoke.com/', config)
return res.data.joke; // res.data.joke를 return해서 저장
} catch (e) {
return "NOPE!" // 에러시 nope
}
}
const addNewJoke = async () => {
const jokeText = await getDadJoke()
const newLI = document.createElement('li');
newLI.append(jokeText);
jokes.append(newLI)
}
document.querySelector('button').addEventListener('click', () => {
addNewJoke();
})
'The Web Developer 부트캠프 2022' 카테고리의 다른 글
TV 프로그램 API 응용 (0) | 2022.09.27 |
---|---|
API AXIOS 이용한 TV 프로그램 (0) | 2022.09.26 |
AXIOS (0) | 2022.09.26 |
Fetch API (2) | 2022.09.26 |
JSON parese, stringify, API 요청 종류, Http statue (0) | 2022.09.26 |