DEV Community

AKSH DESAI
AKSH DESAI

Posted on

Part 4:- Try Catch javascript Syntax

Javascript Code

let btn = document.getElementById("btn");
const makeRequest = async (e) => {
    e.preventDefault();
    let title = document.getElementById("title").value;
    let desc = document.getElementById("desc").value;
    try {
        const init = {
            "method": "POST",
            "headers": {
                "Content-Type": "application/json"
            },
            "body": JSON.stringify({
                title: title,
                desc: desc
            })
        }
        console.log(init);
        const res = await fetch("http://127.0.0.1:8000/student/", init);
        console.log('res', res);
        if (!res.ok) {
            throw new Error(res.statusText);
        }
        const data = await res.json();
        console.log(data)
    } catch (error) {
        console.log("error", error);
    }
}
btn.addEventListener('click', makeRequest);
Enter fullscreen mode Exit fullscreen mode

Thank You.
You can follow us on:
Youtube
Instagram

Top comments (0)