Ila
Ila

Reputation: 195

Cross Origin Domain Blocking in ajax Image Search API (Google)

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.

Upvotes: 0

Views: 1251

Answers (2)

Sébastien Renauld
Sébastien Renauld

Reputation: 19672

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.

Upvotes: 1

Piotr Dajlido
Piotr Dajlido

Reputation: 2030

Cross-Origin Request Blocked That is it, this a policy that prevents from fetching sources from places other than origin. You are actually faking the XMLHttpRequest HTTP Referer Header. with this : xhr.setRequestHeader('Referer', 'http://www.mydomainexample.com'); and you are not allowed to spoof referrers because they're an important part of the security model.

At least what you are looking for is Cross-origin resource sharing.

Read about CORS here : http://enable-cors.org/server.html

Upvotes: 0

Related Questions