본문 바로가기
Web Development/JavaScript

28. AJAX and API's

by 사향낭 2022. 1. 5.

284. Intro to AJAX

 

- Asynchronous JavaScrip And XML

- A new approach to using a number of existing technologies together, including HTML or XHTML, CSS, JavaScript, DOM, XML, XSLT, and most importantly the XMLHttpRequest object.

- It allows web applications to make quick, incremental updates without reloading the page.

- JSON is used in most case instead of XML

 

 

285. Intro to APIs

 

- Application Programming Interface

- Connection between computers, or between computer programs.

- Web browser can request data to web server, and get response through web API.

 

 

286. JSON

 

- JavaScript Object Notation

- A lightweight data-interchange format (Its notation is similar with JavaScript Object, but it is just a format)

- JSON.parse(jsonObject) : JSON (JavaScript String) to JavaScript Object

- JSON.stringify(jsObject) : JavaScript Object to JSON (JavaScript String)

( If a value is undefined in JavaScript Object, the corresponding key-value pair is removed after JSON.stringify )

 

const jsonObject = '{"name": "James", "Age": 15}' // JavaScript String

// { Age: 15, name: "James" }
const jsObject = JSON.parse(jsonObject) // JavaScript Object
const jsObject = {name: "James", age: 15} // JavaScript Object

// '{"name": "James", "age": 15}'
const jsonObject = JSON.stringify(jsObject) // JavaScript String

 

 

287. Using Postman

 

- Postman is an API platform for building and using APIs.

- Nice debugging tool :)

 

 

288. Query Strings & Headers

 

- key-value pairs that we can request to url.

- Which one we use is determied by API specification.

 

 

289. Making XHR's

 

- Old version of JavaScript request to the server

 

const req = new XMLHttpRequest();

req.onload = function () {
    console.log("SUCCESS");
    const data = JSON.parse(this.responseText);
    console.log(data.url)
}

req.onerror = function () {
    console.log("ERROR!!!");
}

req.open('GET', 'https://api.tvmaze.com/singlesearch/shows?q=girls');
req.send();

 

 

290. The Fetch API

 

- The newer way of making requests via JS

- Supports promises

- Not supported in Internet Explorer

 

# Promise version

fetch('https://api.tvmaze.com/singlesearch/shows?q=girls')
    .then(response => {
    	// A representation of the entire HTTP request (It does not have the data we want)
        console.log("Response success, but waiting to pass", response);
        // So the next promise for waiting the data
        return response.json();
    })
    .then(data => {
        console.log("Data passed");
        console.log(data.url);
    })
    .catch(e => {
        console.log("ERROR!!! because of", e);
    })

 

# Async version

const getUrl = async () =>  {
    try {
        const response = await fetch('https://api.tvmaze.com/singlesearch/shows?q=girls');
        const data = await response.json();
        console.log(data.url);
    } catch(e) {
        console.log("ERROR!!!", e);
    }
}

 

 

291. Intro to Axios

 

- Axios is promise based HTTP client for the browser and node.js

- It does not need to wait for data.

- It's not built-in library of JavaScript, so we have to link the Axios library.

 

APPEND THIS TO OUR HTML FILE (Using CDN) (In the head tag prefered)

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

 

# Promise version

axios.get('https://api.tvmaze.com/singlesearch/shows?q=girls')
    .then(response => {
        console.log(response.data.url);
    })
    .catch(error => {
        console.log("ERROR!", error);
    })

 

# Async version

const fetchUrl = async () => {
    try {
        const response = await axios.get('https://api.tvmaze.com/singlesearch/shows?q=girls')
        console.log(response.data.url);
    } catch (e) {
        console.log("ERROR!", error);
    }
}

 

 

292. Setting Headers With Axios

 

- Just add the header object as second parameter to the "axios.get" method

 

 

LET'S MAKE A CLICK & JOKE WEBSITE

 

# HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <title>Document</title>
</head>

<body>
    <h1>Click to get new jokes!</h1>
    <button>Click me!</button>
    <ul class="jokes"></ul>

    <script src="app.js"></script>
</body>

</html>

 

# JavaScript

const makeJoke = async () => {
    try {
        const config = { headers: { Accept: 'application/json' } }
        const response = await axios.get('https://icanhazdadjoke.com', config)
        return response.data.joke
    } catch (error) {
        console.log("ERROR!", error);
    }
}

const jokes = document.querySelector('.jokes')

const writeJoke = async () => {
    const jokeText = await makeJoke();
    const joke = document.createElement('li')
    joke.append(jokeText)
    jokes.append(joke)
}

const button = document.querySelector('button')
button.addEventListener('click', writeJoke);

 

# Result

293. TV Show Search App

 

# HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <title>Document</title>
</head>

<body>
    <h1>TV Show Serach</h1>
    <form id="searchForm">
        <input type="text" placeholder="TV Show Title" name="query">
        <button>Search</button>
    </form>
    <script src="app.js"></script>

</body>

</html>

 

# JavaScript

const form = document.querySelector('#searchForm')
form.addEventListener('submit', async function (e) {
    e.preventDefault()
    const searchTerm = form.elements.query.value
    const config = { params: { q: searchTerm } }
    const res = await axios.get('https://api.tvmaze.com/search/shows', config)
    console.log(res.data)
    res.data.forEach((tvShow) => {
        if (tvShow.show.image) {
            const img = document.createElement('img')
            img.src = tvShow.show.image.medium
            document.body.append(img)
        }
    })
    form.elements.query.value = ''

})

 

# Result

 

'Web Development > JavaScript' 카테고리의 다른 글

29. Prototypes, Classes, & OOP  (0) 2022.01.15
27. Async JavaScript  (0) 2022.01.04

댓글