Last active
December 9, 2019 22:33
-
-
Save gustavohenrique/9cc7dedc03aa7eb3f7de397e3debe959 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
* GET using promises | |
*/ | |
function startRequest() { | |
// show loading | |
var params = { id: 123 }; | |
makeRequest(params).then(function (body) { | |
// hide loading | |
console.log('Response body:', body); | |
}) | |
.catch(function(error) { | |
// hide loading | |
console.log('Error:', error.message); | |
}); | |
} | |
function makeRequest(params) { | |
return new Promise(function(resolve, reject) { | |
var client = new XMLHttpRequest(); | |
var url = 'http://anyurl/' + params.id; | |
client.open('GET', url); | |
client.onreadystatechange = function() { | |
if (client.readyState == XMLHttpRequest.DONE) { | |
if (client.status == 200) { | |
resolve(JSON.parse(client.responseText)); | |
} | |
else { | |
reject({message: 'Eita, deu erro ' + client.statusText}); | |
} | |
} | |
} | |
client.send(); | |
}); | |
} | |
/* | |
* POST no promises | |
*/ | |
var client = new XMLHttpRequest(); | |
client.open('POST', 'http://url/v1/optout/123', true); | |
client.setRequestHeader('Content-type', 'application/json'); | |
var payload = { | |
"productId": 1319, | |
"largeAccount": 8080, | |
"url": "https://dominio:porta/{roleId}", | |
"countryId": 55, | |
"transactionUUID": "edaf587b-91e1-11e7-a2de-005056b152d8" | |
}; | |
client.send(JSON.stringify(payload)); | |
client.onreadystatechange = function() { | |
if (client.readyState == XMLHttpRequest.DONE) { | |
if (client.status == 200) { | |
console.log('Parece que deu certo.', client.responseText); | |
console.log('headers', client.getAllResponseHeaders()); | |
console.log('Content-Type', client.getResponseHeader('Content-Type')) | |
} | |
else if (client.status == 400) { | |
console.log('Fuuuuuu. Voce enviou um request zoado.'); | |
} | |
else { | |
console.log('Deu algum erro no servidor.', client.responseText); | |
} | |
} | |
}; | |
// https://xhr.spec.whatwg.org | |
// Fetch | |
try { | |
const data = await postData('http://example.com/answer', { answer: 42 }); | |
console.log(JSON.stringify(data)); // JSON-string from `response.json()` call | |
} catch (error) { | |
console.error(error); | |
} | |
async function postData(url = '', data = {}) { | |
// Default options are marked with * | |
const response = await 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 | |
}); | |
return await response.json(); // parses JSON response into native JavaScript objects | |
} | |
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment