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?
Solution 1:
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','*');