Last active
February 20, 2019 08:49
-
-
Save rubinhozzz/442f2163237428ce4fd02a8ce93ebf02 to your computer and use it in GitHub Desktop.
Sends a request through fetch using async / await.
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
/** | |
* Sends a request through fetch using async / await. | |
* @param {Object} request | |
*/ | |
async function makeRequestCall(request) { | |
const response = await fetch(request); | |
const json = await response.json(); | |
if (!response.ok) { | |
let error = new Error(response.statusText); | |
error.response = response; | |
error.errors = json; | |
throw error; | |
} | |
return json; | |
} | |
let data = serializeForm(document.getElementById('form_text')); | |
let request = new Request(urls.addSpecificationDetail, { | |
method: 'POST', | |
credentials: 'include', | |
headers: new Headers({ | |
'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8', | |
'X-Requested-With': 'XMLHttpRequest', | |
'X-CSRFToken': getCookie('csrftoken'), | |
}), | |
body: data, | |
}); | |
makeRequestCall(request) | |
.then(jsonResponse => console.log(jsonResponse)) | |
.catch(error => { | |
console.log(error.errors); | |
writeErrorsFromAjaxForm('form_text', error.errors, 'id_text'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment