Validate Fetch JSON response for #1703

This commit is contained in:
the-djmaze 2024-08-13 00:02:51 +02:00
parent 0dedeb0180
commit 6d477aa6ec

View file

@ -4,6 +4,7 @@ const
qUri = path => doc.location.pathname.replace(/\/+$/,'') + '/?/' + path,
eId = id => doc.getElementById('rl-'+id),
admin = '1' == eId('app').dataset.admin,
mimeJSON = 'application/json',
toggle = div => {
eId('loading').hidden = true;
@ -92,7 +93,7 @@ window.rl = {
}
}
if (asJSON) {
init.headers['Content-Type'] = 'application/json';
init.headers['Content-Type'] = mimeJSON;
postData = JSON.stringify(postData);
}
init.body = postData;
@ -104,9 +105,13 @@ window.rl = {
fetchJSON: (resource, init, postData) => {
init = Object.assign({ headers: {} }, init);
init.headers.Accept = 'application/json';
init.headers.Accept = mimeJSON;
return rl.fetch(resource, init, postData).then(response => {
if (response.ok) {
const ct = response.headers.get('Content-Type');
if (!ct.startsWith(mimeJSON)) {
return Promise.reject(new Error(`Invalid Content-Type '${ct}' for url '${resource}'`));
}
/* TODO: use this for non-developers?
response.clone()
let data = response.text();
@ -126,7 +131,7 @@ window.rl = {
*/
return response.json();
}
return Promise.reject('Network response error: ' + response.status);
return Promise.reject(new Error('Network response error: ' + response.status));
});
}
};