TIL: Today I Learned
[TIL] 20201212 AJAX and API's
김알리
2020. 12. 13. 17:23
AJAX
- Asynchronous Javascript And Xml
- Nowadays most APIs use JSON instead of XML
- Creates applications where we can fatch, load, and send data without refreshing the whole page.
API
- Application Programming Interface
- Web API : Web-based Interfaces. HTTP based.
- Can retrieve the information we need.
JSON
- JavaScript Object Notation
- A format for sending data
- Has key-value pair
- Can't store JavaScript value 'undefined', so it's changed to null
- Syntax
{
"key1" : value1,
"keyN" : valueN
}
- How to change a JSON data to a JavaScript object
JSON.parse(jsonData)
- How to change a JavaScript object to a JSON data
JSON.stringfy(javaScriptObject)
Postman
- API development environment
- Helps building and testing Web APIs
- Headers
- key-value pair
- Metadata for the response and request
- HTTP response status codes
- 2** : Successful responses
- 3** : Redirection messages
- 4** : Client error responses
- 5** : Server error responses
Query Strings
- Information that we can provide to as a part of a url that usually impacts the resulting information.
- url example
- /search/shows?q=:query
- http://api.tvmaze.com/search/shows?q=new
- If some information that the api doesn't recognize gets passed in the url, it will be just ignored.
Headers
- Has infos about the request
- Every API is different. Read the document.
XHR
- Xml Http Request
- The 'original' way of sending requests via JavaScript.
- Doesn't support promises, so lots of callbacks.
- Difficult Syntax
- Example
const myReq = new XMLHttpRequest();
myReq.onload = function() {
const data = JSON.parse(this.responseText);
console.log(data);
};
myReq.onerror = function(err) {
console.log('Error', err);
}
myReq.open('get', 'http://icanhasdadjoke.com', true);
myReq.setRequestHeader('Accept', 'application/json');
myReq.send();
Fetch API
- The newer way of making requests via JavaScript
- Supports promises
- Not supported in Internet Explorer
- Syntax
fetch(url) //returns a promise
.then(res => {})
.catch(err => {})
//or,
async function() {
try{
const res = await fetch('url')
const data = await res.json();
} catch(e) {
//code
}
}
- As soon as fetch retrieves the headers, it is going to resolve the promise.
- json() : returns a promise of JSON, when all the info came through.
Axios
- A library for making HTTP requests
- Easier to use then XHR and fetch
- To install : Visit their page and add their script to the HTML before the script for .js file. (Even can be put in the head)
- get('url') : returns a promise whose data is already parsed into JSON. Doesn't have to call res.json()
Setting Headers with Axios
Example
const getDadJoke = async () => {
const config = {headers: {Accept : 'application/json'}};
const res = await axios.get('http://icanhasdadjoke.com/', config);
}
* This post is a summary of Udemy Course "The Web Developer Bootcamp" by Colt Steele.