amol-jore
amol-jore

Reputation: 91

Javascript equivalent for curl command

I am using below curl command to get the data from Druid cluster hosted on remote server, in the json format

curl -X POST "http://www.myserverIP.com:8080/druid/v2/" -H 'content-type: application/json' -d '{"queryType": "groupBy","dataSource": "twsample","granularity": "none","dimensions": ["created_at"],"aggregations": [{"type": "count", "name": "tweetcount"}],"intervals": ["2013-08-06T11:30:00.000Z/2020-08-07T11:40:00.000Z"]}'

but I am not able create an equivalent javascript method which will do the same thing, I am using below code to do this.

function sendCurlRequest(){
    var json_data = {
                "queryType": "groupBy",
                "dataSource": "twsample",
                "granularity": "none",
                "dimensions": ["created_at"],
                "aggregations": [
                    {"type": "count", "name": "tweetcount"}
                ],
              "intervals": ["2013-08-06T11:30:00.000Z/2020-08-07T11:40:00.000Z"]
            };
    $.ajax({
         cache : false,       
     type: 'POST',
     crossDomain:true,
     url: 'http://www.myserverIP:8080/druid/v2/',
     data:json_data,
     //dataType: "jsonp",
     contentType:"application/jsonp",
     success: function(data){
            alert(data);
        var pubResults = data;       
     },
     error: function(data){
       alert("ERROR RESPONSE FROM DRUID SERVER : "+JSON.stringify(data));
     },
     complete: function(data){
        console.log("call completed");
     }
   });
}

Any help will be appreciated.

Upvotes: 9

Views: 30548

Answers (1)

PJR
PJR

Reputation: 443

cURL is able to send and receive data cross domain to remote servers but that is not the case with javascript for security reasons

Your options I believe are

1) Use CORS to set headers on the remote server to accept cross domain calls (if you have access to the Server) as also pointed by thriqon

2) Use jsonP format response from the server(again if you have control over how the response is generated or if its already in jsonP format)

3) Write a server-side proxy that acts as the intermediary between your calls and the remote server. You can then format the header or response on the proxy to enable it to respond to cross domain calls

Upvotes: 7

Related Questions