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

3

13

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?

Cheryllches answered 30/6, 2015 at 6:17 Comment(0)
B
4

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.

Blakey answered 8/7, 2015 at 17:17 Comment(2)
I was just wondering. Shouldn't iron-ajax handle this as well, since now it is only usable, for json under the same domain, but not usable for a restful api f.e. when fetching from a subdomain "api.your-project.com"Return
how to do POST request using this element?Dilatation
M
1

You will need to use jsonp -- more info about it here https://en.wikipedia.org/wiki/JSONP

Demo

https://jsfiddle.net/1v2z799o/

Code

$.ajax({
    url: "https://ajax.googleapis.com/ajax/services/search/news?v=1.0&rsz=8&pz=1&cf=all&ned=in&hl=en&topic=tc",

    jsonp: "callback",

    // Tell jQuery we're expecting JSONP
    dataType: "jsonp",

    // Work with the response
    success: function( response ) {
      console.log(response); // server response

    }
});

Result

enter image description here

However i dont see an option in Polymer iron-ajax handleAs for jsonp but try the available options

https://elements.polymer-project.org/elements/iron-ajax

I had a look around and there is byutv-jsonp

The byutv-jsonp element () exposes network request functionality. It is a Polymer v1.0+ element that facilitates making JSONP requests. It uses Polymer behaviors (Byutv.behaviors.Jsonp). It is patterned after Polymer's iron-ajax element (). It has been tested using unit tests. It is part of the BYUtv Elements group of elements.

https://github.com/coderfin/byutv-jsonp

Marks answered 1/7, 2015 at 0:42 Comment(4)
thanks i tried byutv-jsonp... now the issue is Uncaught SyntaxError: Unexpected token : but debugging further found that only {} response gives this error... I tried with different url request and if response with [] will not giving the error.. why? I can't change the googleapi to return []...Cheryllches
@Raja Simon if you check the demo here -- coderfin.github.io/byutv-jsonp/components/byutv-jsonp/demo -- and put this link in the browser -- jsonplaceholder.typicode.com/posts -- you will see the response starts with a -- [ --. and the googles news -- ajax.googleapis.com/ajax/services/search/… -- starts with -- {"responseData": {"results":[ - i wonder if it has a problem with --- {"responseData": {"results": - the callback is actually surrounded by -- [ .. ] -- i saw you raised a ticket issue on github, wait for reply.Marks
@Raja Simon There's also this -- github.com/polymerelements/iron-jsonp-library -- not sure what it does exactly, but check the demoMarks
Ok.. Thanks for all your time. I will check it out iron-jsonp-library and let you know... We will wait..Cheryllches
J
1

I tried JSONPbut it did not work for me. Then I ran my Chrome browser in web security disabled mode and Access-Control-Allow-Origin issue for 3rd party URL being invoked via AJAX requests got resolved for me.

Please note, this is a temporary fix in development environment and it will only work for Chrome.

  1. Create a shortcut of Google Chrome on your desktop or somewhere else
  2. Right click on it > Select Properties
  3. Change target like this:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security

When you run Chrome you will receive a warning that it is running in unsafe mode, but you can ignore it for the time being and continue with development.

Hope this works!

UPDATE: Commands you can try for OSX and Linux/Ubuntu

Being a Windows user I am not very sure about the solutions but but you can give it a try.

Linux:

$ google-chrome --disable-web-security

Command line approach:

chromium-browser --disable-web-security

OSX:

$ open -a Google\ Chrome --args --disable-web-security

To access local files like AJAX or JSON, you can use this flag too. Again, this is strictly for dev purpose.

-–allow-file-access-from-files

NB: You should be careful if you are browsing internet with web security disabled. This will make your PC more vulnerable to attacks!

Remember, you need to close all instances of Chrome and its background apps before you run it in --disable-web-secutiry mode. Let me know if this resolves your issue.

Jute answered 16/11, 2015 at 14:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.