user6827
user6827

Reputation: 1596

CORS jQuery AJAX request

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?

Upvotes: 31

Views: 118988

Answers (1)

yoyo
yoyo

Reputation: 722

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','*');

Upvotes: 52

Related Questions