2013-12-08 35 views
0

我希望能夠直接從節點(使用快遞)將JSON發佈到另一臺服務器。基本上,我不想在調用不同的API時暴露我的api鍵,但仍然可以調用服務。從Express到外部服務器發佈JSON

這就是我想要做的,但是從服務器而不是客戶端: https://github.com/GetResponse/DevZone/blob/master/API/examples/javascript_synopsis.html

從客戶端JS,我想要實現:

 var api_key = 'ENTER_YOUR_API_KEY_HERE'; 

     // API 2.x URL 
     var api_url = 'http://api2.getresponse.com'; 

     function add_contact() { 

      var campaigns = {}; 

      // find campaign named 'test' 
      $.ajax({ 
       url  : api_url, 
       data : JSON.stringify({ 
        'jsonrpc' : '2.0', 
        'method' : 'get_campaigns', 
        'params' : [ 
         api_key, 
         { 
          // find by name literally 
          'name' : { 'EQUALS' : 'test' } 
         } 
        ], 
        'id'  : 1 
       }), 
       type  : 'POST', 
       contentType : 'application/json', 
       dataType : 'JSON', 
       crossDomain : true, 
       async  : false, 
       success  : function(response) {       
        // uncomment following line to preview Response 
        // alert(JSON.stringify(response)); 

        campaigns = response.result; 
       } 
      }); 

      // because there can be only (too much HIGHLANDER movie) one campaign of this name 
      // first key is the CAMPAIGN_ID required by next method 
      // (this ID is constant and should be cached for future use) 
      var CAMPAIGN_ID; 
      for(var key in campaigns) { 
       CAMPAIGN_ID = key; 
       break; 
      } 

      $.ajax({ 
       url  : api_url, 
       data : JSON.stringify({ 
        'jsonrpc' : '2.0', 
        'method' : 'add_contact', 
        'params' : [ 
         api_key, 
         { 
          // identifier of 'test' campaign 
          'campaign' : CAMPAIGN_ID, 

          // basic info 
          'name'  : 'Test', 
          'email'  : '[email protected]', 

          // custom fields 
          'customs' : [ 
           { 
            'name'  : 'likes_to_drink', 
            'content' : 'tea' 
           }, 
           { 
            'name'  : 'likes_to_eat', 
            'content' : 'steak' 
           } 
          ] 
         } 
        ], 
        'id'  : 2 
       }), 
       type  : 'POST', 
       contentType : 'application/json', 
       dataType : 'JSON', 
       crossDomain : true, 
       async  : false, 
       success  : function(response) 
       {       
        // uncomment following line to preview Response 
        // alert(JSON.stringify(response)); 

        alert('Contact added'); 
       } 
      }); 

     } 

回答

3

我認爲您的節​​點服務器可以充當客戶端請求的第三方服務器的代理。

您的服務器可以收集API調用所需的所有輸入參數,如add_contact。您的節點服務器(具有訪問第三方服務器的正確憑證)進行api調用,並將收到的響應傳遞給客戶端。

您可以使用內建的http庫或節點中的the request module(更方便)來進行這些調用。

基本上,你需要爲你需要的外部apis做一個包裝,並且你全部設置好了。

我希望它有幫助。

+0

謝謝,我還沒有機會確定它是否有效,但我絕對試圖完全按照你所描述的(以及更多)。我應該使用請求模塊還是http://nodejs.org/api/http.html#http_http_request_options_callback?你指出的請求模塊有什麼好處? – BRogers

+0

請求模塊使用起來更方便,我建議您使用它。 – vmx

+0

太棒了,再次感謝! – BRogers