Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert command curl to javascript

I'm trying to convert a command in curl to javascript. I have searched in google but I don't find a solution or a explanation that can help me. The command curl is this:

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

With this I want convert the command to $.ajax() function. My problem is that I don´t know what I have to put in function setHeader 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) {
       //
    }
like image 477
seal Avatar asked Oct 09 '14 09:10

seal


People also ask

Can curl be used in Javascript?

To make a GET request using Curl, run the curl command followed by the target URL. Curl automatically selects the HTTP GET request method unless you use the -X, --request, or -d command-line option.

How do I export a curl?

Export Postman to curlClick the Code button (it's right below Save). Select curl from the drop-down menu. Copy the code snippet. In place of APIKEY you should see your actual API key.

How do I convert curl to Python?

Curl Converter automatically generates valid Python code using the Python request library for all provided Curl HTTP headers and Curl data. Enter the Curl command, click Run to execute the command online and check the results. Click Generate Code and select Python to convert the Curl command to Python code.


1 Answers

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");
 }
});
like image 136
Ahmed_Ali Avatar answered Oct 13 '22 13:10

Ahmed_Ali