• axios.get应用,使用dad-joke API生成随机笑话


    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)
  • 相关阅读:
    串口基本知识
    20180826
    20180819
    自动化测试
    说话有重点 测试思维
    学习C语言,在软件测试中如何用?
    PC能替代服务器吗?
    服务器与普通电脑的区别?
    k8s 回滚应用
    k8s Service
  • 原文地址:https://www.cnblogs.com/LilyLiya/p/14334146.html
Copyright © 2020-2023  润新知