Reputation: 123
How can I translate this curl script to an AJAX request in JavaScript?
curl -X POST
-d "grant_type=password&username=admin&password=Demo1234"
-u "<ClientID>:<ClientSecret> " http://<host>/url/to/auth
Upvotes: 2
Views: 440
Reputation: 9753
Here is how you can do it for any curl not just this one:
one of the code snippet exporters is jqueryAjax.
Upvotes: 1
Reputation: 4755
I will show an example in pure JavaScript
function sendData()
{
var formData = new FormData(); //create formData object to send data
formData.append("grant_type, "password"); //via append you add data
formData.append("username", "admin");
formData.append("password", "Demo1234");
var xmlHttp = new XMLHttpRequest(); //create "ajax/xhr" object
xmlHttp.onreadystatechange = function() //monitor status of response
{
if(xmlHttp.readyState === 4 && xmlHttp.status === 200) //if it's ok
{
console.log(xmlHttp.responseText); //then output data
}
}
xmlHttp.open("POST", "http://<host>/url/to/auth");
xmlHttp.setRequestHeader("Authorization", "Basic " + btoa("<ClientID>" + ":" + "<ClientSecret>");
xmlHttp.send(formData);
}
Upvotes: 3
Reputation: 167172
Your curl
call uses three things:
This is what I best came up with:
$.ajax({
"url": "http://<host>/url/to/auth",
"data": "grant_type=password&username=admin&password=Demo1234",
"processData": false,
"beforeSend": function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa("<ClientID>" + ":" + "<ClientSecret>"));
}
});
Replace your <ClientID>
and <ClientSecret>
with the right values.
Upvotes: 2