2015-04-26 53 views
0

我試圖在AWS亞馬遜Linux實例上連接到與我的Web服務器相同的機器上的node.js服務器。當我嘗試使用Ajax與127.0.0.1:8003或localhost:8003上的服務器進行通信時,Firefox中出現「Cross-Origin Request Blocked」錯誤,Chrome中出現「net :: ERR_CONNECTION_REFUSED」。連接到同一AWS實例上的node.js服務器不同的端口,連接被拒絕

如果我直接從瀏覽器訪問機器(即http:[server]:8003),我會得到預期的響應。我也從機器獲得curl localhost:8003的預期響應。我只看到ajax連接的問題。

眼下Node.js的服務器很簡單:

var sys = require('sys'); 
var http = require('http'); 

var server = http.createServer(
    function(request, response) { 

     var origin = "*"; // (request.headers.origin || "*"); 

     if (request.method.toUpperCase() === "OPTIONS"){ 
      // Echo back the Origin (calling domain) so that the 
      // client is granted access to make subsequent requests 
      // to the API. 
      response.writeHead(
       "204", 
       "No Content", 
       { 
        "access-control-allow-origin": origin, 
        "access-control-allow-methods": "GET, POST, OPTIONS", 
        "access-control-allow-headers": "content-type, accept", 
        "access-control-max-age": 10, // Seconds. 
        "content-length": 0 
       } 
      ); 

      // End the response - we're not sending back any content. 
      return(response.end()); 

     } 
     responseBody = "Hello world! from X AWS - version 2\n"; 
     response.writeHead(
      "200", 
      "OK", 
      { 
       "access-control-allow-origin": origin, 
       "content-type": "text/plain", 
       "content-length": responseBody.length 
      } 
     ); 

     response.write(responseBody); 
     response.end(); 
    } 
); 

server.listen(8003); 
console.log("Server running on 8003..."); 

有一個在那裏試圖看看問題是否是與訪問控制允許來源包頭一些額外的代碼。

客戶端頁面也很簡單:

<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
    <title>X BC API Tester</title> 
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 


    <script type="text/javascript"> 
    function call_bc_proxy() 
    { 
     console.log("Calling bc_proxy..."); 
     $.ajax({ 
      type: "GET", 
      url: "http://localhost:8003", 
      dataType: "text", 
      success: function(response){ 
       $("#cms_response").html(response); 
      }, 
      error: function(error){ 

       // Log any error. 
       console.log("ERROR:", error); 

      }, 
     }); 

     return false; 
    } 
    </script> 

</head> 
<body> 
    <p>Test new BCOV API using oAuth2</p> 
    <p><a href="#" onclick="return call_bc_proxy();" class="button">Get token</a></p> 
    <div id="cms_response"></div> 
</body> 
</html> 

我想我可以通過調用通過Ajax PHP函數,並使用PHP函數內捲曲解決該問題,但我想獲得它的工作直接使用Javascript。

任何想法讚賞。不確定其他信息會有用。

JD

回答

1

在瀏覽器中調用http://[server]:8003您的AJAX腳本中使用相同的URL等。當您撥打網址:「http://localhost:8003」時,您正試圖撥打本地電話而不是通話。

+0

Duhhhh。 JavaScript正在瀏覽器的機器上運行。我不得不向負載平衡器添加另一個監聽器,但您的答案解決了這個問題。非常感謝! – unknownrisk

相關問題