fix : now can catch any errors thrown by awaiting req.json()

This commit is contained in:
daragh 2024-01-01 17:16:10 +00:00
parent 7100dad705
commit 7c2a3e6414

View file

@ -1,28 +1,22 @@
export async function post_request(url, body, form_status) {
export async function post_request(url, body, form_status){
let req;
try { try {
req = await fetch(url, { const req = await fetch(url, {
method: 'POST', method: 'POST',
body: JSON.stringify(body), body: JSON.stringify(body),
mode: "cors" mode: "cors"
}); });
} catch (e) {
form_status.innerHTML = `<span style='background-color: red; color: white'>${e}</span>`;
return;
}
if (req.status !== 200) { if (req.status !== 200) {
form_status.innerHTML = "<span style='background-color: red; color: white'>Failure</span>"; form_status.innerHTML = "<span style='background-color: red; color: white'>Failure</span>";
return; return;
} }
let temp = await req.json(); let temp = await req.json();
if (temp.result === 'error') { if (temp.result === 'error') {
form_status.innerHTML = `<span style='background-color: red; color: white'>${temp.error}</span>`; form_status.innerHTML = `<span style='background-color: red; color: white'>${temp.error}</span>`;
} else { } else {
form_status.innerHTML = "<span style='background-color: green; color: white'>Success</span>"; form_status.innerHTML = "<span style='background-color: green; color: white'>Success</span>";
} }
} catch (e) {
form_status.innerHTML = `<span style='background-color: red; color: white'>${e}</span>`;
}
} }