2013-12-08 32 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