I am working on the using fetch with async/await. The fetch api is making a POST request to submit a JSON data on form submission. I am able to submit a data, however, I am not able to show success and failure alert message. It just exit from the function. Is there a way to handle a response on promise return? Below is my code:
try {
const config = {
mode: 'no-cors',
headers: { "Content-Type": "application/json" },
method: "POST",
body: formData
}
const url = "http://localhost:8081/insertEmployeeRequestRecord?" + Math.random();
const response = await fetch(url, config);
if (response.ok) {
debugger;
const res = await response.json()
document.getElementById("lblAlert").innerHTML = res;
// show success message
} else {
throw new Error('Network response was not ok.');
// show error message
}
}
catch (error) {
document.getElementById("lblAlert").innerHTML = error;
// show error message
}
I tried to follow the instruction from https://www.w3schools.com/js/tryit.asp?filename=tryjs_async2 and https://dmitripavlutin.com/javascript-fetch-async-await/. But I didn't get the success with the code. I'm not too much into scripting language. I'm more of the back-end developer. I will appreciate if anyone can help me with the implementation.