31

I'm having troubles with an ajax request. I was getting the error

No 'Access-Control-Allow-Origin' header is present on the requested resource.

So what I tried was this jQuery ajax request:

var request = $.ajax({
    type: 'GET',
    url: url,
    dataType: "json",
    xhrFields: {
        withCredentials: true
    }
});
request.done(function(data){
    console.log(data);
});    

But it is still not working. I am still getting the error.

How should I fix this?

YakovL
  • 7,557
  • 12
  • 62
  • 102
user6827
  • 1,576
  • 5
  • 19
  • 25
  • does API serve `jsonp`? – charlietfl Dec 07 '13 at 14:45
  • I should get this out of it `{"ticker":{"high":0.00061,"low":0.00045,"avg":0.00053,"vol":2284.80958,"vol_cur":4421342.40061,"last":0.00051,"buy":0.00052,"sell":0.00051,"updated":1386427668,"server_time":1386427668}}` – user6827 Dec 07 '13 at 14:48
  • this is a cross domain request issue...google `Access-Control-Allow-Origin` and `same origin policy`. If API doesn't serve `jsonp` will need to use a server proxy to obtain data – charlietfl Dec 07 '13 at 14:50

1 Answers1

52

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');
ytbryan
  • 2,644
  • 31
  • 49
yoyo
  • 722
  • 6
  • 4