How to solve No 'Access-Control-Allow-Origin&#

2020-03-01 07:26发布

问题:

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

But no matter what i tried below error is coming, even i tried with Github pages 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 the functionality will 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...

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

回答1:

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.



回答2:

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

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



回答3:

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.