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

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.

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:">

If the Cordova Whitelist plugin doesn't work out for you, you can use the Cordova advanced Http plugin to make calls to external servers.
Install using:
cordova plugin add cordova-plugin-advanced-http
Link to plugin:
https://github.com/silkimen/cordova-plugin-advanced-http?ref=hackernoon.com
Extra info:
https://hackernoon.com/a-practical-solution-for-cors-cross-origin-resource-sharing-issues-in-ionic-3-and-cordova-2112fc282664

If you just experienced the issue starting Aug 1 2019. This Access-Control-Allow-Origin Error..(using cordova) might be related to the problem.

I have added following in nodejs server which solves my issue;
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
This may be helpful if you are using nodejs.
Thanks

There is no need to do such thing
You just try to change the permission
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>

I found the solution for my similar scenario, was getting the error:
"access-control-allow-origin cannot contain more than one origin"
Eventually I found that although I had set my .net core API to allow all sources like so:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
...
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
...
I had then left an old CORS command in the web.config file in the website root of the API:
<customHeaders>
<add name="Access-Control-Allow-Origin" value="https://localhost:444" />
</customHeaders>
I commented out the customHeaders section and it worked.
Mission accomplished!

Related

Ajax requests are failing on Cordova Android app

When I ran the project on Chrome browser the ajax requests worked fine but when I installed the app on Android the requests are not working anymore.
This is the code:
var xhr=new XMLHttpRequest()
xhr.onerror=function(){
var message=alert(txt('Please turn on mobile data or Wi-Fi','Ligue os dados moveis ou Wi-Fi'))
}
xhr.onreadystatechange=function (){
if (this.status== 200 && this.readyState == 4){
alert("trye")
eval(xhr.responseText)
}
}
xhr.open("POST",`http://dpreaction.ml?i=js`)
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
xhr.send()
the config.xml file
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.teste.teste" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>DP Reaction</name>
<description>Inrease your things</description>
<author email="gilluisfrancisco70#gmail.com" href="http://dpreaction.ml">
DP Reaction
</author>
<content src="index.html" />
<allow-intent href="*" />
<access origin="*" />
<allow-naviation href="*" />
</widget>
And this is my tag:
<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
According to https://github.com/apache/cordova-android/issues/1354:
Content-Security-Policy is a different security mechanism than CORS (Cross-Origin Resource Sharing).
In cordova-android#10, they implemented a WebAssetLoader, which proxies requests through the https://localhost protocol. The WebAssetLoader acts like a private web server only accessible to your app. This was done because some web view features require you to be in a "secure context" (e.g. HTTPS) for the features to be enabled. In doing so, it does enable CORS enforcement.
Cordova android 9.x uses the plain old file system (file://), which didn't enforce CORs. This is why you see the XHR request work in 9. x but not in 10. x. You can make 10. x behave like 9. x by enabling the AndroidInsecureFileModeEnabled
So if you are using cordova-android#10 just add the following preference at config.xml:
<preference name="AndroidInsecureFileModeEnabled" value="true" />
I had the same problem and it solved it for me. :)

Cordova Audio Stream issue on Android 10

I am trying to play audio stream for a radio channel using cordova, The code runs well on all mobile phones but on Huawei Pro 30 it is not able to load the and throwing this error when using direct
<audio controls src='mystreamurl' id="myaudio" />
Failed to load resource: the server responded with a status of 401 (Authentication Required)
I have tried to use cordova-plugin-media and made sure that all permissions are there :
it throws error code 0
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
and have added to the application tag
android:usesCleartextTraffic="true"
and my html meta tag
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src * 'self' http://* https://* 'unsafe-inline'; script-src * 'self' http://* https://* 'unsafe-inline' 'unsafe-eval';img-src * 'self' https: blob: data: http:; media-src * 'self' 'unsafe-inline' http://* https://* ;font-src *" />
Kindly note as mentioned before on all other phones it is working but on huawei having androird 10 not working and I have double checked the application settings and permissions on the phone all seems to be right.
**EDIT : I found that the issue is not in the code but the issue in authorization on the link in Android 10 ,
this Link is http://acc.qatarnavigator.com/news/music.html which contains the audio src (http://shaincast.caster.fm:44928/listen.mp3?authn3a123cb80bd23dbc6bee1f8156e8c8a0) is working fine.
If I added it as a iframe the Android 10 also block the media link (Failed to load resource: the server responded with a status of 401 (Authentication Required)
So the question now is there any work arround to authorize the link? is because it is not encoding it correctly ?
Note if I play any other online media .mp3 link it is working
I have tested to create
CLICK ME
Then it Throws an error
err_cleartext_not_permitted
So I have added due to Network configuration new rules
<?xml version="1.0" encoding="utf-8"?>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">shaincast.caster.fm:44928</domain>
</domain-config>
But again it throws the error :
Failed to load resource: the server responded with a status of 401 (Authentication Required)
Any Ideas?
**

Ajax calls fail when running Android Cordova app in Release mode

AJAX calls fail when running the app in release mode on Android (works on iOS). This is the error (a warning really) I see in the Chrome Dev Tools:
Provisional headers are shown
Request URL:https://server.com/api/index.php?ticket=ST-111111-ABCDEFG-cas
Request Headers
Provisional headers are shown
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Origin:file://
User-Agent:Mozilla/5.0 (Linux; Android 6.0; Google Nexus 5 - 6.0.0 - API 23 - 1080x1920 Build/MRA58K) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/40.0.0.0 Mobile Safari/537.36
Query String Parametersview sourceview URL encoded
ticket:ST-111111-ABCDEFG-cas
Form Dataview sourceview URL encoded
request:{"param1":"val1","param2":"val2"}
Everything works fine on Debug mode.
My last year release build for Android is still working fine also. So it may be related to the new version of Cordova.
Here is the tools versions I have:
Node version: v4.4.3
Cordova version: 6.2.0
cordova-android#5.1.1
Android SDK up to date
I did set these settings in the config.xml:
<allow-navigation href="*" />
<access origin="*" />
<allow-intent href="*" />
I am using the whitelist plugin:
<plugin name="cordova-plugin-whitelist" spec="1" />
I also set this meta in the index.html file:
<meta http-equiv="Content-Security-Policy" content="default-src *; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
Is there other Cordova settings I forgot to set?
FYI, I have removed and re-addd the Android platform to my project, updated all my plugins but I still get the same Ajax error.
Please help.
Had exactly the same problem. $.ajax works fine on debug version. Release Version fails with status code 0.
Issue was a week SSL certificate. I changed the https to http and then it worked in release too. See:
https://forum.ionicframework.com/t/cordova-plugin-whitelist-problem-only-in-release/43705/3
From API side api developers need to allow cross origin headers.
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: CUSTOM_HEADERS);
header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS);
Also when request come from cordova or using ajax, then there ajax request two call:
first call is for options, in which api returns only allowed headers & methods
after that second is actual api call which call api.

Unable to access cross domain web service in Cordova

I am trying to post some data to an express.js server. The client side is a cordova app. I can successfully post content using a browser but unable to do so using the cordova app.
When I attempt, I get an error: POST https://192.xx.x.1:8081/test 404 (Not Found). Upon using the Chrome device inspector the following is seen
Request URL:https://192.xx.x.1:8081/test
Request Method:POST
Status Code:404 Not Found (from cache)
Here are few more things that I have added:
In config.xml
<allow-navigation href="*" />
The cordova whitelist plugin is already installed.
In index.html and scan.html pages, I have added
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
I have also made sure that the AndroidManifest.xml file contains:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Here is the code for the POST request
$.ajax({
type : "POST",
url : app.url,
crossDomain: true,
data : {username : 'asd', password : 'sadsfa'},
dataType : 'json',
success : function(response) {
$('#result').text("response");
},
error : function(error) {
alert(JSON.stringify(error));
} });
Finally I tried clearing the application cache. Nothing works. None of the request reaches the server side. What am I missing out?
Are you setting <access origin="*" /> in your config.xml file?
Also, if you are using jQuery Mobile as your UI framework, do a $.mobile.allowCrossDomainPages = true; when you receive the deviceready notification.

Issue with Android Hybid app to display remote image with Ionic framework?

I am new to Ionic.
I am using Ionic Framework (1.3.20), Angular JS, Cordova 5.0.0
Template file browse.html code:
<div class="col-50"><img ng-src="{{availableImages[currentImage].src}}" /></div>
app.js code:
.state('app.browse', {
url: "/browse",
views: {
'menuContent': {
templateUrl: "templates/browse.html",
controller: 'Ctrl'
}
}
})
controller.js code
.controller('Ctrl',function($scope) {
$scope.currentImage = 0;
$scope.availableImages = [
{
src: "http://lorempixel.com/160/160/people/3"
}
];
console.log("reading image in controller !!!");
})
Header details:
Request URL:http://lorempixel.com/160/160/people/3
Request Method:GET
Status Code:404 Not Found (from cache)
Response Headers
Client-Via:shouldInterceptRequest
Request Headers
Provisional headers are shown
Accept:image/webp,*/*;q=0.8
User-Agent:Mozilla/5.0 (Linux; Android 5.0.2; XT1033 Build/LXB22.46-28; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/42.0.2311.129 Mobile Safari/537.36
Config.xml file:
<access origin="*"/>
Error on console:
GET http://lorempixel.com/160/160/people/3 404 (Not Found)
I verified the url http://lorempixel.com/160/160/people/3 is showing image in my mobile browser. but the image is not coming on the app.
Whitelisting the domains using cordova-plugin-whitelist solves the issue.
Add the plugin via CLI:
cordova plugin add cordova-plugin-whitelist
and then add the following line of code to your app's config.xml:
<allow-navigation href="http://*/*" />
and
this meta tag in your index.html
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
EDIT: The reason for this issue:
From Cordova 4.0.0 for Android's update:
Whitelist functionality is revamped
You will need to add the new cordova-plugin-whitelist plugin to continue using a whitelist
Setting a Content-Security-Policy (CSP) is now supported and is the recommended way to whitelist (see details in plugin readme)
Network requests are blocked by default without the plugin, so install this plugin even to allow all requests, and even if you are
using CSP.
This new whitelist is enhanced to be more secure and configurable, but the Legacy whitelist behaviour is still available via a separate
plugin (not recommended).
Note: while not strictly part of this release, the latest default app
created by cordova-cli will include this plugin by default.
Build this plnkr: http://plnkr.co/edit/GprtU3r8NDgYwO6jGRkp?p=preview
My html file:
<div><img ng-src="{{ availableImages[currentImage].src }}" /></div>
Javascript:
$scope.currentImage = 0;
$scope.availableImages = [{
src: "http://lorempixel.com/160/160/people/3"
}];
It seems that everything is alright...
Tested with angularjs 1.3.15

Categories

Resources