I am new to ajax. I tried using ajax get method for Google Image search (Deprecated API). For some reasons my client is preferring Deprecated API than Custom Search. When I make a request it says
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=8&start=0&imgsz=xlarge,large&q=apple. This can be fixed by moving the resource to the same domain or enabling CORS.
But when i call this via browser url it responds with perfect response.
My ajax request
$.ajax({
type : "GET",
url : "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=8&start=0&imgsz=xlarge,large&q=apple",
beforeSend : function(xhr) {
xhr.setRequestHeader('Referer', 'http://www.mydomainexample.com');
},
success : function(result) {
console.log(result)
},
error : function(error) {
console.log(error)
}
})
Pardon me for any mistakes. Please help me out.
Ah, CORS. The source of so many weird bugs.
What actually happens below the hood is a preflight OPTIONS request, which contains an Origin header. This Origin is the domain and protocol you are currently on. The server returns a set of CORS headers (Access-Control-Allow-Origin and co), which then tell the browser whether they should be allowed to go through with the request.
If the Origin and CORS headers do not match, it throws the error you encountered. There is no way around this in browser, if you really want it to work, you're going to have to proxy the API.