问题描述:

I'm trying to use AJAX to get a piece of string from a local server made using node.js, the connection is being done, status 200, everything is working but I still can't get the piece of string. May someone provide me an explanation of why this is happening?

P.S.: I'm still a newbie to node.js

Node.js server code:

// 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 Call code:

<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>

Console:

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 often fails the ajax call because of violation of same origin policy. Therefore, you need to modify your code and remove crossDomain : true,. Also, add a timeout:5000, or write async: false, for safe side.

It will work then.

相关阅读:
Top