Search code examples
javascriptjsonxmlhttprequest

XMLHttpRequest appending payload to the uri


I'm making a simple POST XMLHttpRequest, it is successfully posting the data but also the paylod getting appended to the URL. Is there anyway the data doesnt appended to the URL

var payLoad= JSON.stringify(ItemJSON);                                                                      
var xmlhttp = new XMLHttpRequest();                                                                 
xmlhttp.addEventListener("readystatechange", function () {                                          
  if (xmlhttp.readyState < 4){                                                                      
    }                                                                                               
    else if (xmlhttp.readyState === 4) {                                                            
      if (xmlhttp.status == 200 && xmlhttp.status < 300){                                         
            console.log("Success",xmlhttp.responseText);                                            
        }                                                                                          
    }else{                                                                                          
        alert("Error!! \\n There was an error while saving. Please retry again later.");        
                }                                                                                           
        });                                                                                                 
        xmlhttp.open("POST", URL, false);                                                                   
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");                       
        xmlhttp.send(payLoad);  
}

Response : https://sample.com/api/apipipelines?apiName=asdasdaaaaaa&orgUnit=ASA&apiProductName=asdasd&leadDeveloperName=Sandeep&leadDeveloperEmail=sa11as1%40sandsssy.com&baseUrl=%2Fapplication%2Foip%2Fv1%2Fcase-management%2F&projectOwnerName=alisa&projectOwnerEmail=sa%40sasssssndy.com


Solution

  • It is because the header that you used while posting the content:

     xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
    

    Change it to

    xmlhttp.setRequestHeader("Content-Type", "application/json");
    

    Reference for you: What is the difference between form-data, x-www-form-urlencoded and raw in the Postman Chrome application?