I’ve got several Meteor apps that heavily rely on ajax get requests. At some point, one of these apps stopped being able to send ajax get requests, on recent versions of Android, only.
The same app works in the browser, on iOS, and on older versions of Android. (Or rather, on a Fire tablet.) So, I take this to mean this is not a CORS issue.
Other apps, using the same code, are not affected, on any platform.
It appears to me that Android is blocking the requests, and I don’t understand how to make this work.
Also, I've not found a device with recent version of Android where this does work, meaning it's not just my phone.
This is an example request:
$.ajax({
type: "GET",
traditional: true,
url: url,
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: {},
success: function (result) {
...
},
error: function (xhr) {
var propValue;
for(var propName in xhr) {
propValue = xhr[propName]
$("#log").prepend(propName + ": " + propValue + "<br />");
}
}
});
This is the output:
statusText: error
status: 0
responseText:
error: function(){return o&&(n&&!t&&(s=o.length-1,a.push(n)),function t(n){p.each(n,(function(n,r){p.isFunction®?e.unique&&l.has®||o.push®:r&&r.length&&“string”!==p.type®&&t®}))}(arguments),n&&!t&&u()),this}
success: function(){return o&&(n&&!t&&(s=o.length-1,a.push(n)),function t(n){p.each(n,(function(n,r){p.isFunction®?e.unique&&l.has®||o.push®:r&&r.length&&“string”!==p.type®&&t®}))}(arguments),n&&!t&&u()),this}
complete: function(){return o&&(n&&!t&&(s=o.length-1,a.push(n)),function t(n){p.each(n,(function(n,r){p.isFunction®?e.unique&&l.has®||o.push®:r&&r.length&&“string”!==p.type®&&t®}))}(arguments),n&&!t&&u()),this}
progress: function(){return o&&(n&&!t&&(s=o.length-1,a.push(n)),function t(n){p.each(n,(function(n,r){p.isFunction®?e.unique&&l.has®||o.push®:r&&r.length&&“string”!==p.type®&&t®}))}(arguments),n&&!t&&u()),this}
fail: function(){return o&&(n&&!t&&(s=o.length-1,a.push(n)),function t(n){p.each(n,(function(n,r){p.isFunction®?e.unique&&l.has®||o.push®:r&&r.length&&“string”!==p.type®&&t®}))}(arguments),n&&!t&&u()),this}
done: function(){return o&&(n&&!t&&(s=o.length-1,a.push(n)),function t(n){p.each(n,(function(n,r){p.isFunction®?e.unique&&l.has®||o.push®:r&&r.length&&“string”!==p.type®&&t®}))}(arguments),n&&!t&&u()),this}
pipe: function(){var e=arguments; return p.Deferred((function(n){p.each(t,(function(t,o){var a=p.isFunction(e[t])&&e[t]; i[o[1]]((function(){var e=a&&a.apply(this,arguments); e&&p.isFunction(e.promise)?e.promise().progress(n.notify).done(n.resolve).fail(n.reject):no[0]+“With”}))})),e=null})).promise()} promise: function(e){return null!=e?p.extend(e,r):r}
then: function(){var e=arguments; return p.Deferred((function(n){p.each(t,(function(t,o){var a=p.isFunction(e[t])&&e[t]; i[o[1]]((function(){var e=a&&a.apply(this,arguments); e&&p.isFunction(e.promise)?e.promise().progress(n.notify).done(n.resolve).fail(n.reject):no[0]+“With”}))})),e=null})).promise()}
always: function(){return i.done(arguments).fail(arguments),this}
state: function(){return n}
abort: function(e){var t=e||w; return l&&l.abort(t),C(0,t),this}
statusCode: function(e){var t; if(e)if(b<2)for(t in e)v[t]=[v[t],e[t]]; else T.always(e[T.status]); return this}
overrideMimeType: function(e){return b||(f.mimeType=e),this}
setRequestHeader: function(e,t){var n=e.toLowerCase(); return b||(e=x[n]=x[n]||e,y[e]=t),this}
getAllResponseHeaders: function(){return 2===b?a:null}
getResponseHeader: function(e){var t; if(2===b){if(!c)for(c={}; t=Pt.exec(a); )c[t[1].toLowerCase()]=t[2]; t=c[e.toLowerCase()]}return null==t?null:t}
readyState: 0
Any insight would be greatly appreciated.
Check your SSL on backend.
Since Android 9, your api end point must :
Use HTTPS
Not be self-signed
Use public certificate authority
only
Related
Ajax request not sending on android studio with cordova. I tried a simple request to google but it does not work either.
What i already tried :
- Change minSdk to 23
- Add cordova whitelist plugin and permissions for https and http in config.xml
- add android:usesCleartextTraffic="true" in AndroidManifest
- i have nothing in my network profiler but ajax return a timeout error
- Outside my app, my request work
Code
$.ajax({
type: "POST",
url: OAUTH2_URL,
cache : false,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', make_base_auth($("#login").val(), $("#pwd").val()));
},
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: json,
timeout: 5000,
success: function (data) {
etape3(data);
},
error: function (xhr, ajaxOptions, thrownError){
SpinnerPlugin.activityStop();
navigator.notification.confirm(
'login or password incorrect.', // message
null, // callback
'Error', // title
['Ok'] // buttonName
);
}
})
I don't know what else to do
Thanks !
I have an app in IONIC and in browser the call to API works but when I run on android device it shows this error:
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://192.168.1.***:8080/api/auth/login", ok: false, …}
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://192.168.1.***:8080/api/auth/login: 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "http://192.168.1.***:8080/api/auth/login"
__proto__: HttpResponseBase
In IONIC I send like API_URL = 'http://192.168.1.***:8080/api/'; to use HttpClient, and in Laravel I run php artisan serve --host 192.168.1.*** --port 8080
Please, someone knows what I should do to work?
The issue is related to CORS. You don't have to do anything to your IONIC app. You can enable CORS request by adding required headers for that you can create your own middleware in Laravel to handle cors, A sample middleware would be:
namespace App\Http\Middleware;
use Closure;
class Cors
{
public function handle($request, Closure $next)
{
return $next($request)->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', '*');
}
}
Then use it, by editing app\Http\Kernel.php
protected $middlewareGroups = [
'web' => [
// middleware for your web routes
],
'api' => [
'throttle:60,1',
'bindings',
'cors',
],
]
protected $routeMiddleware = [
// other middleware code
'cors' => \EuroKids\Http\Middleware\Cors::class,
]
You can customize the above middleware as required.
However, if you don't want to do create your own middleware you can use this library:
https://github.com/barryvdh/laravel-cors
I develope an App with Phonegap and Jquery Mobile. For some reasons I also need to get data from https domains. On IOS everything works perfect, but on Android I always get the following errors and the requests fails
06-17 17:16:33.890 6079-6154/de.sistecs.einlass E/chromium_net: external/chromium/net/socket/ssl_client_socket_openssl.cc:905:
[0617/171633:ERROR:ssl_client_socket_openssl.cc(905)] handshake failed; returned -1, SSL error code 1, net_error -107
Here is a simple sample code
$(document).on("pageinit", function (event, ui) {
$("#test").click(function () {
$.ajax({
type: "POST",
url: "https://test.sistecs.de/sismedia/test.php",
success: function (response) {
$("#testmsg").text(response);
}
});
});
});
I´ve read hundreds of posts, but didn´t find a solution to my problem.
The certificate of the server https://test.sistecs.de/sismedia/test.php is valide.
Can someone help me?
It seems like a Cross Origin problem.
With jQuery Mobile you should set $.mobile.allowCrossDomainPages and $.support.cors to true
<script>
$( document ).on( "mobileinit", function() {
$.mobile.allowCrossDomainPages = true;
$.support.cors = true;
});
</script>
Also be sure that your PHP page sets the headers accordingly. For example:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,PUT,POST,DELETE');
header('Access-Control-Allow-Headers: Content-Type');
echo "test";
?>
Edit: I didn't test the code, it is an example. Adapt as you need to.
var myJson = {
'Par1': 'par'
};
$.ajax({
url: baseUrlAjaxServices + "/....",
data: JSON.stringify(myJson),
method: "POST",
crossDomain: true,
dataType: 'json',
contentType: 'application/json',
})
.done(function (data) {
//...
}).fail(function (error) {
console.log(error);
});
I am developing Android application using PhoneGap. I am trying to execute simple login module, it works fine in web browser. But when it comes to apk, its not working. It is not able to post request to Restful API.
var usr = $('#email_address').val();
var pass = $('#password').val();
if(usr != '' && pass != ''){
alert("Before Calling Method");
$.ajax({
url:APIURL +"api/sample/sample123",
type: "POST",
crossDomain : true,
data: {username:usr,password:pass},
dataType: "json",
success: function(data){ /*Here I am posting some dummy code, I can't show original code*/
var response = eval(data);
alert(response.response);
}
});
When I am executing this on android phone, I am getting only first alert above i.e "Before Calling Method" but it is not showing another alert. I have configured res/xml/cordova.xml as
<access uri="*" subdomains="true"/>
Also I have referred some previous related doubts from StackOverflow. But It didn't helped me. Please help me to, I am waiting for positive response...
try this one
formData = {
username: $('#email_address').val(),
password: $('#password').val()
}
$.ajax({
url: APIURL + "api/sample/sample123",
type: "POST",
crossDomain: true,
contentType: 'application/json',
data: formData,
dataType: "json",
success: function(data) {
alert(data);
}
});
I'm developing a app with PhoneGap/Cordova 2.5.0 and I'm making AJAX calls with jQuery 1.8.2 to retrieve datas from an external server. I'm doing a lot of requests and I can see my app cache growing up, and this is not pretty cool...
I've tested many things like :
$.ajaxSetup({
cache: false,
headers: {
"Cache-Control": "no-cache"
}
});
OR / AND
var ajaxRequests = {}; // Limit one AJAX call for each "data_id" to prevent numbers calls
if (vrbd.ajaxRequests[data_id] === undefined) {
ajaxRequests[data_id] = $.ajax({
type: 'GET',
dataType: 'xml' + data_id,
url: url,
data: {
_: new Date().getTime() + Math.random()
},
async: true,
timeout: (data_count >= 2 ? data_count * 800 : 2000),
cache: false,
headers: {
"Cache-Control": "no-cache"
}
})
.done(function(data, textStatus, jqXHR) { ... })
.fail(function(jqXHR, textStatus, errorThrown) { ... })
.always(function(jqXHR, textStatus) { delete ajaxRequests[data_id]; });
}
If I let my app running during a couple of hours, I can see my cache growing up from about 160kb to about 30Mb in Settings > Apps > MyApp > Cache (AVD and real device).
So, didn't I understand anything about the cache in Settings or did I forget something ?
Please, let me know if you need another informations, sorry for my english, and thanks in advance for your help.
Best regards
Alex
Clear cache:
// clear cache
super.clearCache();
super.loadUrl("file:///android_asset/www/index.html");
Source:
Adding a splash screen and clearing cache with PhoneGap and Android