• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LilyLiya
博客园    首页    新随笔    联系   管理    订阅  订阅
axios.get应用,使用dad-joke API生成随机笑话
按钮点击事件(addEventListener);async; await; axios.get; document.createElement('LI');

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)

 

posted on 2021-01-27 11:39  LilyLiya  阅读(249)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3