거위발바닥 2022. 9. 26. 16:30
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();
})