最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cross domain ajax json - Stack Overflow

programmeradmin1浏览0评论

I'm on site trying to grab some json data from my node.js server serving on port 8080.

I get this Error message:

XMLHttpRequest cannot load :8080/json/1. Origin  is not allowed by Access-Control-Allow-Origin.

my code:

    $.get(':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 ':8080/' + this.id
    }
});

Is there any way to resolve this other than using jsonp?

Thanks.

I'm on site. 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.:8080/json/1. Origin http://site. is not allowed by Access-Control-Allow-Origin.

my code:

    $.get('http://site.: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.:8080/' + this.id
    }
});

Is there any way to resolve this other than using jsonp?

Thanks.

Share Improve this question asked Feb 14, 2011 at 0:30 FriiSourceFriiSource 3212 gold badges6 silver badges12 bronze badges 2
  • 9 The ports must match as well, otherwise jsonp is indeed the only option. – Pekka Commented Feb 14, 2011 at 0:35
  • I'm having the same issue. IMHO, this should be clarified in the documentation (that ports are considered to be part of the domain). Also, are requests across subdomains illegal as well? – snapfractalpop Commented Mar 30, 2012 at 14:59
Add a ment  | 

3 Answers 3

Reset to default 7

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.". You can learn more about CORS here: http://www.w3/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.

发布评论

评论列表(0)

  1. 暂无评论