2016-10-01 63 views
0

我有一個RAILS API。AJAX返回net :: ERR_CONNECTION_REFUSED

當我從終端打電話給它正確的結果。現在我試圖從外部應用程序調用該API。

捲曲:

curl -H 'Accept: application/vnd.marketplace.v1' http://api.market_place_api.dev:3000/users/1 

關於捲曲正常工作。現在

我的外部文件的代碼是:

1234.html

<!DOCTYPE html> 
<html> 
    <head> 
     <title>API Testing</title> 
     <script src="https://code.jquery.com/jquery-2.2.4.min.js" crossorigin="anonymous"></script> 

     <script type="text/javascript"> 
      $.ajax({ 
       headers: { Accept : "application/vnd.marketplace.v1"}, 
       url: "http://api.market_place_api.dev:3000/users/1", 
       type: 'GET', 
       contentType: 'application/json', 
       data: { auth_token: "Vb6BQdPQNx9uD_wczkeW"}, 
       success: function (data) { 
        alert(JSON.stringify(data)); 
        $('div.jsonoutput').append(JSON.stringify(data)); 
       }, 
       error: function(){ 
        alert("Cannot get data"); 
       } 
      }); 
     </script> 
    </head> 

    <body> 
     <div><center><p><strong>API Request &amp; Response Testing</strong></p></center></div> 

     <div class="jsonoutput"></div> 

    </body> 
</html> 

回答

0

這些行添加到application_controller

控制器:

protect_from_forgery with: :exception, if: Proc.new { |c| c.request.format != 'application/json' } 
protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' } 

腳本:

<script type="text/javascript"> 
     $.ajax({ 
      url: "http://api.market_place_api.dev:3000/users/1", 
      type: 'GET', 
      contentType: 'application/json', 
      data: { auth_token: "Vb6BQdPQNx9uD_wczkeW"}, 
      success: function (data) { 
       alert(JSON.stringify(data)); 
       $('div.jsonoutput').append(JSON.stringify(data)); 
      }, 
      error: function(){ 
       alert("Cannot get data"); 
      } 
     }); 
    </script>