我尝试使用AJAX从使用node.js
制作的本地服务器获取一段字符串,连接正在完成,状态200,一切正常但我仍然无法做到得到一块绳子。有人可以向我解释为什么会这样吗?
P.S。:我还是node.js
Node.js
服务器代码:
// Load the http module to create an http server.
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/javascript"});
response.end("var a = 'Hello World';");
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
AJAX
来电代码:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.ajax({
async: 'false',
type: 'GET',
url: 'http://127.0.0.1:8000/',
success: function(data, textStatus){
console.log('DONE: Request has been successfully sent');
},
error: function(xhr, textStatus, errorThrown){
console.log('ERR: Request failed \nSTATUS: '+textStatus+'\nERROR: '+errorThrown);
console.log(xhr);
}
});
</script>
控制台:
XMLHttpRequest cannot load http://127.0.0.1:8000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
XHR failed loading: GET "http://127.0.0.1:8000/".send @ jquery-latest.min.js:4m.extend.ajax @ jquery-latest.min.js:4(anonymous function) @
ERR: Request failed
STATUS: error
ERROR:
Object {readyState: 0, responseText: "", status: 0, statusText: "error"}
答案 0 :(得分:0)
Cross domain
violation
, same origin policy
经常无法通过ajax调用。因此,您需要修改代码并删除crossDomain : true,
。
另外,为了安全起见,请添加timeout:5000,
或写async: false,
。
它会起作用。