Created
January 23, 2019 12:52
-
-
Save YordanGeorgiev/0d2dfa568ea0aad6e93078f62cfea263 to your computer and use it in GitHub Desktop.
[get-server-data-with-axious] how-to get server data with axios #javascrit #axios #get
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="https://unpkg.com/axios/dist/axios.min.js"></script> | |
<script> | |
function getUrlParams (){ | |
var url_params = new URLSearchParams(); | |
if( window.location.toString().indexOf("?") != -1) { | |
var href_part = window.location.search.split('?')[1] | |
href_part.replace(/([^=&]+)=([^&]*)/g, | |
function(m, key, value) { | |
var attr = decodeURIComponent(key) | |
var val = decodeURIComponent(value) | |
url_params.append(attr,val); | |
}); | |
} | |
// for(var pair of url_params.entries()) { consolas.log(pair[0]+ '->'+ pair[1]); } | |
return url_params ; | |
} | |
function getServerData (url, urlParams ){ | |
if ( typeof url_params == "undefined" ) { urlParams = getUrlParams() } | |
return axios.get(url , { params: urlParams } ) | |
.then(response => { | |
return response ; | |
}) | |
.catch(function(error) { | |
console.error ( error ) | |
return error.response; | |
}) | |
} | |
// Action !!! | |
getServerData(url , url_params) | |
.then( response => { | |
if ( response.status === 204 ) { | |
var warningMsg = response.statusText | |
console.warn ( warningMsg ) | |
return | |
} else if ( response.status === 404 || response.status === 400) { | |
var errorMsg = response.statusText // + ": " + response.data.msg // this is my api | |
console.error( errorMsg ) | |
return ; | |
} else { | |
var data = response.data | |
var dataType = (typeof data) | |
if ( dataType === 'undefined' ) { | |
var msg = 'unexpected error occurred while fetching data !!!' | |
// pass here to the ui change method the msg aka | |
// showMyMsg ( msg , "error") | |
} else { | |
var items = data.dat // obs this is my api aka "dat" attribute - that is whatever happens to be your json key to get the data from | |
// call here the ui building method | |
// BuildList ( items ) | |
} | |
return | |
} | |
}) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment