axios.get('/user/12345')
.catch(function (err) {
if (err.response) {
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
} else if (err.request) {
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of http.ClientRequest in node.js
console.log(err.request);
} else if(!err.status) {
console.log(err.message);
} else {
console.log('Error', err.message);
}
console.log(err.config);
});
Builtin to modern browsers, adds parse step compared to axios and some other gotchas
fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
Response.status
.json()
.text()
Advanced Fetch
fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json", // "Content-Type": "application/x-www-form-urlencoded",
},
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
body: JSON.stringify(data), // body data type must match "Content-Type" header
})
.then(response => response.json());
function encodeQueryData(data) {
const ret = [];
for (let d in data)
ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d]));
return ret.join('&');
}
OG Fundamental
var http = new XMLHttpRequest();
http.open("GET", "url", true); //true if we want it to be synchronous
http.send();
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
//...........
//usually update DOM somehow
}
}
Parse JSON Response
Could also send and receive XML, but nahhhhh JSON.parse(http.responseText); JSON.parse is only avaliable in most modern browsers, could use lib like jQuery