fetch
api call:
csrf token
when submitting the formFormData
is used to send the files to the action properly when using an Uploader
classfunction getMetaValue(name) {
// Alternative to obtaining the CSRF token ---> Rails.csrfToken()
let element = document.head.querySelector(`meta[name="${name}"]`);
return element.getAttribute("content");
}
function uploadFile(data, file, counter) {
// let data = new FormData();
data.append('product_image[image]', file);
data.append('product_image[title]', file.name);
fetch('/summit/products/' + prodId + '/product_images', {
method: 'POST',
body: data,
credentials: "same-origin",
mode: 'cors',
headers: {
'X-CSRF-Token': getMetaValue("csrf-token")
}
})
.then((result) => {
acknowledgeUpload(counter);
progressDone();
})
.catch((error) => {
alert("Something went wrong, please contact contact your admin for support")
});
}
fetch
does not handle FAILED HTTP codes/does not reject a promise unless a network error occurs!function handleError(response) {
if (!response.ok) {
throw Error(response.textStatus)
}
return response.text();
}
fetch()
.then(handleErrors)
.then(() => {
// code
})
.catch((error) => {
// more code to alert the user of error
)