当 AJAX-get 在本地主机上与 node.js 时收到错误消息

Getting error message on while AJAX-get on localhost with node.js

本文关键字:js 消息 错误 node AJAX-get 主机      更新时间:2023-09-26

我正在尝试使用 AJAX 从使用 node.js 制作的本地服务器获取一段字符串,连接正在完成,状态为 200,一切正常,但我仍然无法获取该字符串。有人可以给我解释为什么会发生这种情况吗?

PS:我还是新手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"}

Cross domain经常因为same origin policy violation而使ajax调用失败。因此,您需要修改代码并删除crossDomain : true, 。此外,为了安全起见,请添加timeout:5000,或写入async: false,

然后它会起作用。