我正在尝试在AWS Amazon Linux实例上连接到与我的Web服务器相同的计算机上的node.js服务器。当我尝试使用Ajax在127.0.0.1:8003或localhost:8003与服务器通信时,我得到一个"跨源请求被阻止" Firefox出错," net :: ERR_CONNECTION_REFUSED"使用Chrome。
如果我直接从浏览器访问计算机(即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...");
在那里有一些额外的代码试图查看问题是否与access-control-allow-origin标头有关。
客户端页面也很简单:
<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函数中使用curl来解决这个问题,但我想让它直接用Javascript工作。
任何想法都赞赏。不确定其他信息会有用。
JD
答案 0 :(得分:1)
使用与浏览器调用http://[server]:8003相同的网址作为您的ajax脚本。当您调用网址时:“http://localhost:8003”您试图调用本地计算机而不是aws。