Home > Back-end >  How to convert this curl cmd to jQuery $.ajax()
How to convert this curl cmd to jQuery $.ajax()

Time:07-24

I'm trying to make a api call with jquery ajax.

curl --request POST \
--url https://test.stytch.com/v1/passwords/strength_check \
-u 'PROJECT_ID:SECRET' \
-H 'Content-Type: application/json' \
-d '{
    "password": "jvx-kbj4nbj7ZKP9ncv"
}'

I tried ajax like this, but it is not working:

$.ajax({
url: "https://test.stytch.com/v1/passwords/strength_check",
beforeSend: function(xhr) { 
  xhr.setRequestHeader("Authorization", "Basic "   btoa("PROJECT_ID:SECRET")); 
},
type: 'POST',
dataType: 'json',
contentType: 'application/json',
processData: false,
data: '{"password":"jvx-kbj4nbj7ZKP9ncv"}',
success: function (data) {
  alert(JSON.stringify(data));
},
error: function(){
  alert("Cannot get data");
}
});

What am I wrong ? Thanks

CodePudding user response:

var url = "https://test.stytch.com/v1/passwords/strength_check";

var xhr = new XMLHttpRequest();
xhr.open("POST", url);

xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Basic UFJPSkVDVF9JRDpTRUNSRVQ=");

xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
      console.log(xhr.status);
      console.log(xhr.responseText);
   }};

var data = `{
    "password": "jvx-kbj4nbj7ZKP9ncv"
}`;

xhr.send(data);
  • Related