log, if a network error occurred, an error message
obtain the response data in JSON format
display the data, if available, on the front-end
GET requests
// fill in endpoint hereconsturl=''; // GET or send error// if GET successful, return JSON responsefetch(url).then(response => {if (response.ok) {returnresponse.json(); }thrownewError('Request failed!');}, networkError => {console.log(networkError.message);}).then(jsonResponse => {return jsonResponse;});
POST requests
With POST requests, we add one more argument to fetch - the data we will POST:
// fill in endpoint hereconsturl='';// provide POSTing data as JSON object hereconstdataBody= { whatever:"here" };// set up the data payloadconstdata= { method:'POST', body: dataBody };// POST or die// if POST successful, return the confirmation as JSONfetch(url, data).then(response => {if (response.ok) {returnresponse.json(); }thrownewError('Request failed!');}, networkError => {console.log(networkError.message);}).then(jsonResponse => {return jsonResponse;});
Using async and await (ES8)
ES8 allows us to use async and await keywords:
GET requests
Note the async before the function declaration and the two uses of `await`, one for the fetch response and then another one for the JSON response:
// fill in endpoint hereconsturl='';constgetData=async () => {try {constresponse=awaitfetch(url);if (response.ok) {constjsonResponse=awaitresponse.json(); }thrownewError('Request failed!'); } catch (error) {console.log(error); }}
POST requests
The POST request follows the same pattern as the GET but with an additional argument inside the fetch for the data that we will POST:
The async keyword creates a function that returns a `Promise` to await for responses from the API, before we proceed along the code blocks ... then, we can simply handle any errors and place any valid responses into getData!
Using XMLHttpRequest and JSON.parse
Just for posterity's sake, we have this alternate "old" way to fetch JSON data:
constrequest=newXMLHttpRequest()request.open('GET','data.json',true)request.onload=function() {if (this.status >=200&&this.status <400) {constdata=JSON.parse(this.response) // data hereconsole.log(data) } else {// server error }}request.onerror=function() {// connection error}request.send()