API
fetch('http://api-to-call.com/endpoint').then(response => {
if(response.ok) {
return response.json();
}
throw new Error('Request failed!');
}, networkError => console.log(networkError.message)
).then(jsonResponse => {
return json.response;
});
fetch('https://api-to-call.com/endpoint', {
method: 'POST',
body: JSON.stringify({id: '200'})
}).then(response => {
if(response.ok) {
return response.json();
}
throw new Error('Request failed!');
}, networkError => console.log(networkError.message)
).then(jsonResponse => {
})
//XMLHttpRequest GET
const xhr = new XMLHttpRequest();
const url = 'http://api-to-call.com/endpoint';
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
if(xhr.readyState === XMLHttpRequesty.DONE) {
return xhr.response;
}
};
xhr.open('GET', url);
xhr.send();
//XMLHttpRequest POST
const xhr = new XMLHttpRequest();
const url = 'http://api-to-call.com/endpoint';
const data = JSON.stringify({is: '200'}); // converts data to string
//handle response
xhr.responseType = 'json';
xhr.onreadystatechange = () -=> {
if(xhr.readyState === XMLHttpRequest.DONE) {
return xhr.response;
}
};
//opens request and sends object
xhr.open('POST', url);
xhr.sedn(data);