Search code examples
ajaxpolymerpolymer-1.0

How to solve No 'Access-Control-Allow-Origin' in polymer-project?


I am exploring Polymer-project 1.0 and the task is to get the JSON and print output repeatedly.

But no matter what I tried, the error below is coming. I even tried with Github pages, but this also gives me same error response in terminal.

Error

XMLHttpRequest cannot load https://ajax.googleapis.com/ajax/services/search/news?v=1.0&rsz=8&pz=1&cf=all&ned=in&hl=en&topic=tc. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://rajasimon.github.io' is therefore not allowed access.

Not into theming and designing the material design. All I want is for the functionality to work first. So I wrote below code:

index.html

<iron-ajax
  auto
  url="https://ajax.googleapis.com/ajax/services/search/news?v=1.0&rsz=8&pz=1&cf=all&ned=in&hl=en&topic=tc"
  handle-as="json"
  last-response="{{ajaxResponse}}"></iron-ajax>

  <template is="dom-repeat" items="{{ajaxResponse.responseData.results}}">
        <paper-material elevation="1" class="paper-font-body2">
              <h1>{{item.title}}</h1>
              <iron-image src="[[item.image.url]]" style="width:800px; height:450px; background-color: lightgray;" sizing="cover"  preload fade></iron-image>
              <p>{{item.content}}</p>
        </paper-material>
  </template>

Enabling

For debugging I installed Google Chrome app named Allow-Control-Allow-Origin: *. Then the above code started working.

enter image description here

Even if I tried with iron-ajax demo will give the same result. What's happening here? Am I the one person receiving this error in the universe?


Solution

  • You can solve this problem using byutv-jsonp. It a Polymer 1.0+ element that allows for making JSONP requests. The Google API you are using supports JSONP. I have tested the code below and get back the proper response.

    <byutv-jsonp
        auto
        url="https://ajax.googleapis.com/ajax/services/search/news"
        params='{"v":"1.0","rsz":"8","pz":"1","cf":"all","ned":"in","hl":"en","topic":"tc"}'
        last-response="{{lastResponse}}"
        last-error="{{lastError}}"
        debounce-duration="300"></byutv-jsonp>
    
    <template is="dom-repeat" items="{{lastResponse.responseData.results}}">
        <paper-material elevation="1" class="paper-font-body2">
            <h1>[[item.title]]</h1>
            <iron-image src="[[item.image.url]]" style="width:800px; height:450px; background-color: lightgray;" sizing="cover" preload fade></iron-image>
            <p>[[item.content]]</p>
        </paper-material>
    </template>
    

    It is important to add the query parameters to the params attribute instead of the url attribute with the current version (1.2.0) of byutv-jsonp.