17

I'm trying to convert this curl command to JavaScript:

curl https://www.google.com/accounts/ClientLogin \
  --data-urlencode [email protected] \
  --data-urlencode Passwd=******* \
  -d accountType=GOOGLE \
  -d source=Google-cURL-Example \
  -d service=lh2

I want convert this command to an $.ajax() function. My problem is that I don't know what I have to put in the setHeader function below for the options present in command curl.

$.ajax({
    url: "https://www.google.com/accounts/ClientLogin",
    type: "GET",

    success: function(data) { alert('hello!' + data); },
    error: function(html) { alert(html); },
    beforeSend: setHeader
});


function setHeader(xhr) {
    // ?
}

2 Answers 2

21

By default $.ajax() will convert data to a query string, if not already a string, since data here is an object, change the data to a string and then set processData: false, so that it is not converted to query string.

$.ajax({
 url: "https://www.google.com/accounts/ClientLogin",
 beforeSend: function(xhr) { 
  xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password")); 
 },
 type: 'POST',
 dataType: 'json',
 contentType: 'application/json',
 processData: false,
 data: '{"foo":"bar"}',
 success: function (data) {
  alert(JSON.stringify(data));
},
  error: function(){
   alert("Cannot get data");
 }
});
Sign up to request clarification or add additional context in comments.

Comments

0

If you can use fetch() instead of $.ajax, you can use curlconverter.com/javascript/ and it will convert your command to

fetch('https://www.google.com/accounts/ClientLogin', {
    method: 'POST',
    body: new URLSearchParams({
        'accountType': 'GOOGLE',
        'source': 'Google-cURL-Example',
        'service': 'lh2'
    })
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.