Reputation: 147
I am trying to run a basic Ajax call using JQuery on the client and node.js on the server. the client is loaded from the same server as the one handling the Ajax request - yet i receive on the client side this error:
"XMLHttpRequest cannot load .... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ...... is therefore not allowed access."
I think that the same origin policy surely isn't violated here? maybe local host is treated differently?
server:
httpListen.createServer(function (req, res) {
....
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('_testcb(\'{"message": "Hello world!"}\')');
}
client:
$.ajax({
url: "http://127.0.0.1:1337/",
data : {formType:"ajaxTest", key1:"val1", key2:"vall2"},
formType:"ajaxTest",
jsonpCallback: "_testcb",
cache: false,
timeout: 5000,
success: function(data) {
$("#textBox").text("replied");
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
}
});
this is written after the guidelines of the 1st reply here: how to use jQuery ajax calls with node.js, but i am still getting the said error.
edit: found the problem: using localhost instead of 127.0.0.1, works fine...
Upvotes: 2
Views: 681
Reputation: 1074276
From your question, I see three possibilities:
The Same Origin Policy doesn't just care about server, the port must be the same as well (and the protocol). So a page served from port 80 can't send a request to port 1337 unless you use Cross-Origin Resource Sharing.
Alternately, if you're serving your page from port 1337 (which is the port you're using for your ajax request), be sure you're using the same name for the server both to load the page and to make the request. Note that 127.0.0.1
and localhost
are not considered the same for SOP purposes.
If you're loading your page from the file system rather than the server (e.g., the page's URL starts with file://
, you double-clicked the file in a file explorer or something to open it), then the problem is that pretty much everything is different, starting with the protocol (file:
!= http:
).
Upvotes: 5