I'm building an app that gets data from a server using basic user authentication. This works fine on Android, but on iOS nothing happens. In safari it also works fine.
This is the code I'm using:
$.ajax({
url: main_url+'api-cache/'+slug+'.json?r='+random_number(),
dataType: 'json',
headers: {
'Authorization': "Basic " + btoa(localStorage.getItem('email') + ":" + localStorage.getItem('password'))
}
})
.done(function(result) {
main_url is a link to an https website.
I have als tried username and passwork like the jQuery documentation says and also beforesend, nothing seems to work. Without the authentication it works fine by the way. Also the result seems to be ".done" because no error is fired in ".fail".
Help? Oh and btw, I'm using Phonegap Build.
Problem solved using a couple of headers on the server instead of changing the app: https://benjaminhorn.io/code/setting-cors-cross-origin-resource-sharing-on-apache-with-correct-response-headers-allowing-everything-through/
Related
I get "Http failure response for https://www.google.com: 0 Unknown Error" when I request from Secured url.
I am trying to test my ionic/angular mobile app. When I tried with http requests I had problem with Android 9, but with Android 7 was working fine. Anyhow I need to set my backend to public https server. So now I'm testing with https request and none of 7 and 9 Android versions works.
I am using Angular 7 ,
"#ionic/angular": "^4.6.1",
"#ionic-native/core": "^5.0.0",
"rxjs": "~6.5.1"
I made these small functions in order to make my problem simpler.
inside my html file i have this code:
myFile.html
<ion-button
(click)="onStartTest()"
>Click me</ion-button>
<p id="testme"></p>
myFile.page.ts
onStartTest() {
this.taskService.onTest().subscribe(result => {
document.getElementById('testme').innerText = 'result ' + result;
console.log(result);
}, error => {
document.getElementById('testme').innerText = error.message;
console.log('Problem ', error.message);
});
}
myTask.service.ts
onTest() {
return this.http.get('https://www.google.com').pipe(
catchError(err => {
return throwError(err);
})
);
}
At first I tried my server's URL but I changed it to "https://www.google.com" just to verify that the backend is correct.
Also I have an interceptors.ts file that I am using it for authentication, but I am not logged in when I execute the onStartTest() function, but im gonna share it anw.
interceptors.ts
import {Injectable} from '#angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '#angular/common/http';
import {Observable} from 'rxjs';
#Injectable()
export class TokenInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.getItem('auth_token');
let newHeaders = req.headers;
if (token) {
console.log(token);
newHeaders = newHeaders.set('Authorization', 'Token ' + token);
const modified = req.clone({
headers: newHeaders
});
return next.handle(modified);
} else {
newHeaders = newHeaders.set('Content-Type', 'application/json');
const modified = req.clone({
headers: newHeaders
});
return next.handle(modified);
}
}
}
I think these are the necessary files to share for this problem.
I also tested the url of google with Postman just to be sure that I should get a status 200
I am also aware that there is an "add_header" directive (nginx) that adds 'Allow-access-control-origin' when the response code is 20x or 30x. According to my screenshot with Postman, google is responding with 200 status, but my app still gets status 0 error.
Ignore the first Error. It's a function I use with http when the app begins. Right now im testing https.
I tried superficially to use ionic-native library HTTP but my app totally crashed.
I also execute the command ionic serve --ssl but still nothing.
I read somewhere that for secured connection I need a certificate, but I understood that this is a server's work.
I tried to request from Dark Sky from Vanilla JavaScript and it works fine. So there is something wrong with angular/ionic side and not server's.
What am I missing? I really need to fix this problem soon!
I want to send a secured request to an https url and get the appropriate response.
Your main problem is that you are trying make an API to an unsecure call (http) location (http://192....../mobile/tasks) from a secure origin (https://localhost:8100).
This is clearly indicated in your error message and this is not allowed, and has been answered before
Your second problem is that, for testing purposes, you are trying to call a 3rd party https ressource from your website. This only works if the 3rd party ressource implement CORS, which is not the case for Google and api.darksky.net. Sending a GET request with Postman is useless, as Postman will not check for CORS headers before displaying the response. If you want to use Postman to check CORS, send an OPTIONS request to these ressources and you'll see that there are no CORS headers
So the answer is in MDN - CORS
For security reasons, browsers restrict cross-origin HTTP requests
initiated from scripts. For example, XMLHttpRequest and the Fetch API
follow the same-origin policy. This means that a web application using
those APIs can only request resources from the same origin the
application was loaded from, unless the response from other origins
includes the right CORS headers.
This means the back-end I was using needed some more configuration since I was using 'same-origin' policy script. I thought we had it because when we tried from the browser's console to fetch the request it was working fine, but on mobile it wasn't. We had a custom CORS configuration but we changed it to the django-cors-headers. Since we switched to django-cors-headers I could get correctly the response from HTTP and HTTPs requests.
The other answer and comments were really useful to focus to the right direction.
EDIT: Solution for JQuery Mobile + Phonegap AJAX Problems:
subdomains="true" property in config.xml is not working in phonegap 2.9.0, every request to a subdomain will return 200 but $.ajax won't fire the success function (and $.getJSON won't fire anyways).
Also: Syntax *.domain.tld as stated in the official doc is not working, only way I found to solve that problem: Setting access origin and acces uri to "*" (all)
<access origin="*"/>
<access uri="*"/>
I'm working on a mobile application using the jQuery Mobile Framework and Phonegap.
I've just added an AJAX request to my application which is used to get data from my webserver.
The page is correctly loading but Android (4.1.2) never fires the AJAX event or never gets a request from the Webserver, in fact it's just hanging on the loading spinner.
Strange thing about this is, that I already use an AJAX request to the same server (but with different domain) that works perfectly fine:
$.getJSON("[...]checkupdate.php?callback=?", function(data){
[...]
})
I've tried to do the second request with $.getJSON too and it worked on my computer but failed on Android. I started looking around for a solution and found out, that setting the cache to false in $.ajax might help so I rewrote my code but it's still not working.
$.ajax({
cache : false,
type: 'GET',
url: requestURL,
dataType: 'jsonp',
context: document.body,
success: function(data){
[...]
}});
Is there anything else to do to get this to work?
I found a way to solve that problem. I noticed, that the subdomains="true" property in phonegap's config.xml is not working. (Phonegap 2.9.0). Every request to a subdomain will return status 200 but $.ajax won't fire the success function (and $.getJSON won't fire anyways). The syntax *.domain.tld as stated in the official doc isn't working for me either, only way I found to solve that problem was setting access origin and acces uri to "*" (all)
I have developed a mobile application using :
jquery mobile 1.1
jquery 1.7.2
cordova/phonegap 2.0.0
this application fires AJAX post calls to a remote server, something like:
$.ajax(
type: "post",
cache: false,
timeout: 30000,
url: "http://"+ username+":"+password +"#mycompany.com/mysite/and/so/on.asmx",
contentType: "text/xml",
// other params...
The application works fine in Android 2.2 and 2.3.3. So far so good.
The users have upgraded to Android 4.0.3, the main page loads fine, but ajax calls don't work anymore.
Also in the emulator of android 4.1 it's the same.
Considering nothing else has changed but the platform, what could have changed in the Webkit layer to cause the problem?
Are there known migration rules to be followed?
thank you
Quite a lot of things are more locked down in newer versions of android to improve security. Passwords included in the url are insecure, especially if you don't use https, so some browsers no longer support them.
I haven't seen anything specific to android webview, but it is definitely deprecated in google's other browser.
http://code.google.com/p/chromium/issues/detail?id=123150
Try setting the credentials in a header instead:
$.ajax({
type: "GET",
url: url,
dataType: 'json',
async: true,
data: {},
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', "Basic " + btoa(user + ':' + pass));
},
success: onSuccess,
error: onError
});
Just put <access origin="your server" subdomains="true" /> to config.xml and you are done. No need to rewrite all ajax calls ;-) Just done it with my application and its working fine on all android versions.
I have a index.html with an ajax call to a webservice(ASP.NET) that works fine when i deploy it on the bigrock server(i have a domain).
$.ajax({
type: "POST",
url: "myurl/mywebservice.asmx",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (msg,status) {
$('#demo').html("status is "+status+" . Msg is "+msg.d.responseText);
//attribute for responsetext might be wrong here but in my application it is correct as i am using different system ryt now.
}
});
But when i used the online zipper of phonegap to make a apk for my android app from the html, css,js,web.config,few class and installed it on my device...nothing comes up. Its shows me an ajax error with no responseText.
What am i missing?
When you zip up your assets to submit to PhoneGap Build, you need to include a config.xml file and specify access policy similar to
<access origin="https://your.domain.com" />
This will instruct PhoneGap to allow communication with your server.
When your app is deployed to the device using PhoneGap, your "Home" location becomes the file-system on the local device.
This means any ajax calls are cross-domain calls which require further configuration to setup correctly.
See this question for potential answer
Sending the below request in my phonegapp-ed android app works for GET but not POST.
With GET, everything works. With POST, the request goes through but the POST variables
are not coming through on the server side, and the server returns a
json response that says 'no parameters supplied.'
POST works fine from our mobile app - it is just the phonegap app where we are having an issue. What am i missing here??? Thanks in advance for any help you can provide!
I've tried changing the settings on the $.ajax call, the android manifest, everything I can think of.
Also, i'm using Android 2.2 and Phonegap 1.0
function goTeam(){
var dataString={lat:currentLocation.lat(),lng:currentLocation.lng()}; // this all works
$.ajax({
url: 'http://example.com/request/goTeam',
data: dataString,
dataType: 'json',
success:
function(b) {
if(b.status==1){ // woo hoo! it works
} else {
// the request went through but something was wrong - this is what i'm getting with POST
}
},
type: 'post', // works with GET, doesn't work with POST
error: function(jqXHR, textStatus, errorThrown){ alert("Noooo."); }
});
Are you trying cross-domain requests? Only GET requests work this way. You can use JSONP for this kind of request, but only GET works.
Phonegap does work with both GET and POST - cross-domain security issues do not apply. We had an idiosyncratic error our code that was preventing it from working. Phonegap is pretty awesome!