Fetch API
API: Application Programming Interface
Eine API ist eine Art Übersetzungsprogramm für Programme, die verschiedene Sprachen sprechen. Über eine API können sich Programme austauschen, ohne dass sie wissen müssen, wie das andere Programm funktioniert.
XMLHttpRequest (XHR)
Section titled “XMLHttpRequest (XHR)”XMLHttpRequest ist die alte Methode
XML: Extensible Markup Language (XML hat Ajax erst ermöglicht.)
Ajax: Asynchronous JavaScript and XML
Request -> Server -> Response: Request + Response = Fetch
Request
Section titled “Request”// 1. create an XMLHttpRequest Object:const request = new XMLHttpRequest();// 2. we want to know when a response comes back from the server, so we listen for the load event:request.addEventListener('load', e => { // do sth.});// 3. construct and send the request (we use the method 'get'):const url = "https://my-api-endpoint.tld"; // this is my resourcerequest.open('get', url);request.send();Response
Section titled “Response”The response property contains the data.
The response is a JSON string.
The XHR gives us variuos property/value-pairs like state, timeout, responseURL, withCredentials, …
// XHR in der console ausgeben:request.addEventListener('load', e => { console.log(e.target);});But we are primarily interested in the response property, which contains the requested data from the server (body, payload). The response property is a string, and its value is formatted in JSON. To work with these data, we have to convert them to JavaScript first.
JavaScript Object Notation
JSON Objects are similar to JavaScript Objects with two main differences:
- JSON objects contain only strings
- JSON property/value-pairs are always, always wrapped with double quotes
There are two methods to convert JSON to JavaScript and vice versa:
- JSON to JavaScript:
JSON.parse(el); - JavaScript to JSON:
JSON.stringify(el);
request.addEventListener('load', e => { const blubb = JSON.parse(e.target.response); console.log(blubb); // we don't want to have all the data, so we "massage" them // we create a new array which contains only the information we need const data = blubb.map(blu => { return { name: blu.name, url: blu.html_url, stars: blu.stargazers_count, }; });});Fetch API
Section titled “Fetch API”The Fetch API is the newer method to perform Ajax.
The .fetch() method takes in two arguments:
- url: address you want the information from
- options (opt.): a JavaScript object that lets you provide extra options
fetch() sends out the request immediately. To see the response, we need a then() statement.
The response looks different: it is hidden in the body property as a readable stream. To use this stream, we have to convert it to JavaScript. fetch() contains the method json(), which does this for us.
fetch() uses Request and Response objects as well as CORS and HTTP Origin header semantics. It returns a Promise that resolves to the Response to that Request.
const url = "https://my-api-endpoint.tld";fetch(url)// to read the response directly, we can log it to the console:.then(response => console.log(response))// remove the console.log to continue:.then(response => response.json()).then(data => console.log(data))