我试图在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
Duhhhh。 JavaScript正在浏览器的机器上运行。我不得不向负载平衡器添加另一个监听器,但您的答案解决了这个问题。非常感谢! – unknownrisk