refer to: https://www.udemy.com/course/the-web-developer-bootcamp/
使用icanhazdadjoke.com API 生成jokes: https://icanhazdadjoke.com/api#fetch-a-random-dad-joke
使用axios library需要加上:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
https://github.com/axios/axios
API response format
All API endpoints follow their respective browser URLs, but we adjust the response formatting to be more suited for an API based on the provided HTTP Accept
header.
Accepted Accept
headers:
text/html
- HTML response (default response format)application/json
- JSON response(we will use this format)text/plain
- Plain text response
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Axios</title> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> </head> <body> <h1>Click to get new jokes!</h1> <button>Click me!</button> <ul id="jokes"></ul> <script src="app.js"></script> </body> </html>
const jokes = document.querySelector('#jokes'); const button = document.querySelector('button'); const addNewJoke = async () => { const jokeText = await getDadJoke(); const newLI = document.createElement('LI'); newLI.append(jokeText); jokes.append(newLI) } const getDadJoke = async () => { try { const config = { headers: { Accept: 'application/json' } } const res = await axios.get('https://icanhazdadjoke.com/', config) return res.data.joke; } catch (e) { return "NO JOKES AVAILABLE! SORRY :(" } } button.addEventListener('click', addNewJoke)