Axios post on Android device give me Network Error - android

I have an axios call to a presigned url in s3 for upload, this work well in IOS but trow "Netowork Error" in android.
The code is pretty simple but without any other information (the response is empty) I do not kwno how to solve this.
axios.post(presignedPostData.url, formData, config)
.then(function (response) {
})
.catch(function (err) { console.log('S3err',err, err.response) })
I use react-native with expo, the axios call work in ios and also in the web version.
UPDATE
The problem seems relative to formdata, if for example I remove the formdata obviously my post not work but the error (missing pre-conditions...) and the status (412) code are ok, but with formdata I've not error description nor status code..
UPDATE 2: the formdata, autogenerated from s3.createPresignedPost (they work in ios and web)
{"_parts":[["Content-Type","video/mp4"],["key","src-058ef4d0-0d49-11ea-8478-3b47e74a5983.mp4"],["acl","public-read"],["bucket","my.bucket"],["X-Amz-Algorithm","AWS4-HMAC-SHA256"],["X-Amz-Credential","mycredentials"],["Policy","mypolicy"],["X-Amz-Signature","mysignature"],["file",{"cancelled":false,"width":1280,"type":"video","uri":"file:///data/user/0/host.exp.exponent/cache/ExperienceData/%myapp%252Fmyapp/ImagePicker/8d68fafa-5c47-4436-9323-dc0d8702dc5d.mp4","rotation":90,"height":720,"duration":1280}]]}
Also tested with fetch (in place of axios), same problem.
UPDATE 3
If I use FyleSystem
`import * as FileSystem from 'expo-file-system';
//mediaArray['file'] = file;
mediaArray['fileALT'] = FileSystem.cacheDirectory+name
I'm able to du the upload with code 204 but the file uploaded isn't right. Maybe there is a permission problem on imagepicker. Still not working the process but with this new informations maybe someone can have an idea.

the problem seem to be solved, I'm looking to upload video, the file picker add "video" as type, this works on IOS and WEB but not in ANDROID, to get work also in android the type had to be more specific, for example "video/mp4" for .mp4 video o "video/mov" for mov video etc.. I hope that this help someone to achieve mutlipart/form-data in android.

Related

How do I get http content from a https website?

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.

Ionic Cordova web app cookies not being stored on Android or iOS

My company has built a medium size Ionic application and now we're trying to make available natively for Android and iOS and I'm having an issue with persisting cookies.
When running the application Safari there are no issues at all, cookies persist just fine, but when building for devices, the cookies are not being persisted.
The way things work now is when a user logs in, a cookie is returned from the server. After this, the cookie should be sent with every subsequent request, ensuring that the user is still logged in. When I look at the initial response from the server after login, the 'set-cookie' header is there. However, all requests afterward don't contain the cookie, so the server returns a response of not logged in. This only happens when running natively on iOS or Android.
When I debug to see if the cookies are being persisted, I see that there are no cookies.
I know there was a similar issue with iOS 13, but I'm not using iOS 13, I'm using iOS 12. And my problem is on both Android and iOS. When doing Google searches, all the workarounds I see are for problems that are not the same as the one I'm having, and I've tried those workarounds anyways, and they don't work.
Has anyone experienced this issue before? Any ideas on what this might be and how to fix it would be greatly appreciated, I haven't gotten anywhere and I've been searching for an answer for days now.
Also too, because the cookie is HttpOnly I'm not able to access using TypeScript, so I can't persist the cookie manually without sending a non-HttpOnly cookie. Which isn't really an option at the moment.
i had some troubles with cookies and cordova too .
In my case, the plugin cordova-plugin-cartegraph-cookie-master helped me to get and set cookies.
Source Plugin:
https://www.npmjs.com/package/cordova-plugin-cartegraph-cookie-master
Install :
cordova plugin add cordova-plugin-cartegraph-cookie-master
Usage :
Get cookie value :
cookieMaster.getCookieValue('http://<some host>:<some port>', '<cookie name>', function(data) {
console.log(data.cookieValue);
}, function(error) {
if (error) {
console.log('error: ' + error);
}
});
Set cookie value :
cookieMaster.setCookieValue('http://<some host>:<some port>', '<cookie name>', '<cookie value>',
function() {
console.log('A cookie has been set');
},
function(error) {
console.log('Error setting cookie: '+error);
});

Tasker App: Why my HTTP POST is not sending parameters?

I'm making a simple HTTP POST request using Tasker app, it's working fine but somehow it's not sending my arguments. HTTP GET is working fine. What am I doing wrong?
The only thing the server does is JSON stringify all received parameters and return them like: Text: { parameters }
HTTP GET is working:
HTTP POST works, it returns the response "text: {}" but doesn't return any parameter:
Now sometimes it shows "Bad Request Error 400"
I've tested it with another server and this issue persists...
Here's a fiddle to send get and post requests to the same server and both work.
I've exported my task as xml for you to test: You can download it here
Thanks in advance guys!
I have done a little testing with what you have supplied. It appears that your post parameters are making it to the server but %HTTPR is not getting populated. The Tasker documentation says that this variable will be populated if the response is "text-based", but this does not seem to be the case. I may not know what Tasker considers to be "text-based", but I have tried "text/plain" and "text/html" with no luck.
The work-around that I have come up with is to put the response into a file using the "Output File" field of the post task. (Leave "Content Type" blank or this won't work.) You can then read the file into a variable and do what you need to.
This is either a defect in Tasker, incorrect documentation, or just a misunderstanding of what it takes to make it work. This work-around, however, will get you what you need.
Here is a link to a GitHub repository with the updated task export. You may need to change the output file name/location to work with your device.
Update:
Since I posted the above solution, I have run across a Tasker plugin called "RESTask for Tasker". Evidently, Tasker has enough issues with HTML requests that a separate plugin was needed. I have tested this plugin with POST and it does work, so this is another way to go. The plugin is available on the Google Play store.

Phonegap jQuery.ajax requests works on AVD but fails on real device

I have this annoying problem on my app PhoneGap that the request below works fine on my web browser and my AVD, but fails on device, I keep getting readyState 0, can anyone help?
var appCredentials = "client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET";
function loadVenues(){
var url = "https://api.foursquare.com/v2/venues/search?";
var ll = "&ll=-23.6057,-46.6662&limit=4";
var request = url+appCredentials+ll;
$.ajax({
dataType: "json",
url: request,
success: loadVenuesSuccess,
error: error
});
}
function error(param1, param2, param3){
alert(JSON.stringify(param1));
alert(param2);
alert(param3);
}
Please note that it works on both browser and AVD.
Had the same issue, in my case the problem was my url contained htaccess information like (http://username:mypassword#www.domain.com/.....)
took me hours to find that bug in phonegap (works on every others plattform, also the avd etc, only on the real device not.)
Not sure that is your problem, but it might give you a hint were to investigate further...

phonegap android ajax requests work for GET but not POST

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!

Categories

Resources