Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

javascript - CORS + Cordova : issues with : Access-Control-Allow-Origin

I have been searching hours on this issue, but I still can't find any solution to this.

I am developping an App cordova (basicely HTML / JS) So : the app runs on mobile from the navigator, and I have trouble making an ajax request to an API : https://developer.riotgames.com/ But let's say that I just want to get the google page.

How on earth do I do that, is this even possible ? Here is a simple exemple :

$.ajax({
    type: "GET",
    url: "https://google.com",
    dataType: "text",
    success: function(response){
        alert("!!!");
    },
    error: function(error){
        alert("...");
    }
});

I am getting the same error again and again :

XMLHttpRequest cannot load https://google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access

The origin 'null' is because I run the code from : file:///D:/Projets/LoL/www/index.html and I read that the navigator is blocking, but it doesn't work as well if I disable the security with --disable-web-security And of course, I don't have access to the server I want to join.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need the Cordova whitelist plugin: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-whitelist/.

Have this in config.xml:

<access origin="*" />
<allow-navigation href="*"/>

And have the Content-Security-Policy meta in index.html. Something like:

<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data:">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...