Cross domain ajax json
I'm on site.com trying to grab some开发者_开发百科 json data from my node.js server serving on port 8080.
I get this Error message:
XMLHttpRequest cannot load http://site.com:8080/json/1. Origin http://site.com is not allowed by Access-Control-Allow-Origin.
my code:
$.get('http://site.com:8080/1/', {}, function (Data) {
console.log(Data);
}, "json");
But it is the same domain though! :(
Also consider my backbone.js model:
model = Backbone.Model.extend({
url: function() {
return 'http://site.com:8080/' + this.id
}
});
Is there any way to resolve this other than using jsonp?
Thanks.
If you're making the call to the same domain, why do you have the absolute path in your $.get
request?
Try this:
$.get('/1/', {}, function (Data) {
console.log(Data);
}, "json");
model = Backbone.Model.extend({
url: function() {
return '/' + this.id
}
});
If you are truly making the call on the same domain, then the above code should work.
Alternatively, you could modify your node.js server to allow Cross-Origin Resource Sharing (CORS). This only works in modern browsers. The simplest (and least secure) thing to do would be for your node.js server to emit the header "Access-Control-Allow-Origin: http://site.com". You can learn more about CORS here: http://www.w3.org/TR/cors/
You have to make the call to the same domain and port your script was loaded from. You should be able to use jmort's code.
精彩评论