0

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.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
MPR
  • 1
  • 1
    You said `no-cors` so you forbade yourself access to the response. – Quentin Nov 01 '22 at 14:41
  • @Quentin I am getting error failed to fetch on removing the no-cors. Can you share the example. – MPR Nov 01 '22 at 14:50
  • Can I share what example? It's your code. You need CORS permission to read the response. Saying you want `no-cors` says you don't want that permission so you can't read the response. If you don't have permission then not saying `no-cors` isn't *sufficient* to solve the problem but it is the essential first step. – Quentin Nov 01 '22 at 14:51
  • @Quentin I will try to apply the change and will update you. – MPR Nov 01 '22 at 15:00

0 Answers0