'I am trying to make a post request using javascript to my fast api app. But it is giving error INFO. 422 Unprocessable Entity

// variables for getting Original URL
const form2 = document.getElementById("form2");
const resultContainer2 = document.querySelector(".result__container2");
const longUrl = document.querySelector(".longurl");

//for decoding the url (Retrieving Original URL)
form2.addEventListener("submit", (e) => {
    e.preventDefault();
    var formData = new FormData();
    formData.append("shortUrl", e.target.shortUrl.value);
    formData.append("customCode", e.target.shortUrl.value);
    let data = {}
    for(let pair of formData.entries()) {
        data[pair[0]] = pair[1]
    }

    console.log(data)

    let xhr = new XMLHttpRequest();
    xhr.open("POST", "/api/v2/original", true);

    // Set the request header
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onreadystatechange = function() { 
        if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
            console.log("Done")
        }
    }

    //Displaying the Original long URL
    xhr.onload = function () {
        const response = JSON.parse(this.responseText);
        console.log(this.status);
        console.log(response);
        if(this.status ==200) {
            resultContainer2.style.display = "flex";
            longUrl.innerHTML = `ORIGINAL LONG URL :- <a href=${response.longUrl}>${response.longUrl}</a>`
        }
        else {
            alert(`An error occurred, ${response.detail}`)
        }
    };

    //using JSON for transfering data in between, as per task requirement (JSON Object to JSON string)
    xhr.send(JSON.stringify(data));
})


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source