Cordova FileTransfer: upload image to AWS s3 - angularjs

Am using ng-cordova file-Transfer plugin to upload images to my AWS s3 bucket.
but i run into two problems first it didn't work, second i have no idea how to debug the problem while the App running on the emulater.
here is my code:
.controller('newItemCtrl', function($scope, $http, API_URL, me, $cordovaFileTransfer) {
var s3URI = encodeURI("https://mybucketname.s3.amazonaws.com/"),
policyBase64 = "MY_BASE64_ENCODED_POLICY_FILE",
signature = "MY_BASE64_ENCODED_SIGNATURE",
awsKey = 'my AWSAccessKeyId',
acl = "public-read";
var options = {
fileKey: "avatar",
fileName: "image.png",
chunkedMode: false,
mimeType: "image/png"
// params = {
// "key": fileName,
// "AWSAccessKeyId": awsKey,
// "acl": acl,
// "policy": policyBase64,
// "signature": signature,
// "Content-Type": "image/png"
// }
};
var imageURI = '../img/ionic.png';
$scope.upload = function($cordovaFileTransfer) {
$cordovaFileTransfer.upload(s3URI, imageURI, options)
.then(function(result) {
console.log("SUCCESS: " + JSON.stringify(result.response));
}, function(err) {
console.log("ERROR: " + JSON.stringify(err));
}, function(progress) {
// constant progress updates
});
}
})
I also left the params code to ask another question it's commented, but before i run my app and it gives me an error with the params but my question why i got the error even before invoke the template assosiated with that controller

I had a similar problem, to debug I used the live server logs to check and see if the file upload hit the server at all, some errors I noticed:
my server was expecting a different file key
the Access-Control-Allow-Origin header wasnt being sent properly in the server's response
Then, I also installed the cordova native notifications plugin (link here) and sprinkled alerts throughout the file transfer callbacks to see where things were getting stuck
Anyway probably not the best way to debug, but it worked.
Hope that helps.
...one more thing the params part of "options" seems to work best when applied in this format:
var options = {
fileKey: "avatar",
fileName: "image.jpg",
/*params: {
"value1":"value1",
"value2": "value2"
}*/
};
var params = new Object();
params.value1 = "value1";
params.value2 = "value2";
options.params = params;
from the cordova docs "params: A set of optional key/value pairs to pass in the HTTP request. (Object)" so passing in a dictionary may be subtly different, I'm not sure, all I know is that it worked once I made that change.

To debug on emulator I use this from my app directory: ionic emulate ios -lc
That shows me errors or logs into the console.

Related

How can I access Google Fit data without logging in

I have a web page I am working on, I am wanting to use gapi to access my steps for the day. I do not want to log in every time, I want the page to log in automatically in the background, oAuth2 is required I believe but I can not get any further.
Based on code I've found online and using React with Hooks, I added ts ignore because it could not resolve gapi.
The issue I am having is that I get Login Required error
I've tried using Axios and doing it by API_KEY only. My knowledge on API's is growing but I thought just to access the data an API key would be enough providing I had registered the key in the API tools.
React.useEffect(() => {
const start = () => {
// 2. Initialize the JavaScript client library.
// #ts-ignore
gapi.client.init({
'apiKey': '<API_KEY>',
// clientId and scope are optional if auth is not required.
'clientId': '<CLIENT_ID>.apps.googleusercontent.com',
}).then(function() {
// 3. Initialize and make the API request.
// #ts-ignore
return gapi.client.request({
'path': 'https://www.googleapis.com/fitness/v1/users/<MY_GMAIL_ADDRESS>/dataset:aggregate',
'method': 'POST',
'body': {
"aggregateBy": [{
"dataTypeName": "com.google.step_count.delta",
"dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
}],
"bucketByTime": { "durationMillis": 86400000 },
"startTimeMillis": 1567983600000,
"endTimeMillis": 1568057160150
},
})
}).then(function(response) {
console.log(response.result);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
};
// #ts-ignore
gapi.load('client', start);
}, []);
I just want to be able to return my steps in a JSON object preferably with Axios, if not using the gapi JS library using my React Application. Nothing fancy.
I appreciate this may not be possible but the docs and other questions on stack overflow just are not working for me and no one can answer me.

AWS S3: No 'Access-Control-Allow-Origin' header is present on the requested resource

In my angular app, I have the following error when I try to make an REST api.
My Code is given below:
Angular Controller
$scope.saveTeam = function() {
var club = {};
club.name = $scope.selectedClub;
var service = API.getService();
service.create( {}, { club: club },
function( res ) {
}, function(err) {
console.log("club err : ", err);
});
}
}
Angular Factory
// Clubs service used for communicating with the coaches REST endpoint
angular
.module('app')
.factory('API', ['$resource', 'session', function($resource, session) {
var mainUrl = '/clubs';
return {
getService : function() {
var token = session.getToken();
return $resource(mainUrl, { }, {
createClub: {
method: 'POST',
url: mainUrl,
isArray: false,
headers: { 'Token': token }
}
})
}
}
});
How can I solve this error? Thanks in Advance.
Install this chrome extension to avoid CORS error. This error generally comes because of the security headers in the request made by a client. Use the line of code shown below before making any request to server.
$http.defaults.headers.post["Content-Type"] = "application/json";
Working principles of CORS is a simple HEADERS game between Client and Server. The browser (the client) set in the Origin key the current domain in your case set "http://localhost:9001". The server, in turn, verified that this value is among those trusted and responds with another piece of information (always in the header) with the key Access-Control-Allow-Origin. If the two values are equal, then the browser uses the response, otherwise you will have an error.
So in the future you need to configure the server but for development you can start the Chrome browser with Disable same origin policy. With disable security the browser don't set the origin and you don't have a problem. This is the problem so check this link:
Disable same origin policy in Chrome

ngCordova in Angular JS Web Application

I am not an expert in Angular and have recently started learning it, I am trying to create a responsive form in an AngularJS WEB APPLICATION which will let me upload a file or a photo from a mobile browser (not mobile app). Before I upload anything through my mobile browser, I should check the native settings of my mobile device (not browser settings but the settings of my mobile device).
To achieve this I am using ngCordova with it's wrapper $cordovaFileTransfer. I have a normal project in Eclipse and I have included below files in my index page(I have stored these files locally in my project).
cordova.js
file.js
fileTransfer.js
ng-cordova.js
ng-cordova.min.js
Since I am using Eclipse, I tried to install THyM plugin however it wouldn't install in my work space. Below is my controller code.
angular.module('app').controller(
'CordovaCtrl',
function($scope, $timeout, $cordovaFileTransfer) {
document.addEventListener("deviceready", function(
$cordovaFileTransfer) {
alert("Inside the Cordova Controller - deviceready");
var fileToUpload = "";
var options = {
fileKey : "sendFile",
fileName : "angularJSFileToUpload",
chunkedMode : false,
mimeType : "text/plain"
};
var server = "C:/Dev/Angular file receiver";// Temporary path
var targetPath = "C:/Dev/Angular file sender";// Temporary path
$cordovaFileTransfer.upload(server, targetPath, options).then(
function() {
alert("Success");
}, function(err) {
alert("Error");
});
}, false)
});
I understand that all plugin calls should be wrapped in the "deviceready" event. Whenever I run my project I get below error on the browser console.
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8080/fileupload/cordova/cordova_plugins.js
Uncaught TypeError: Object #<Event> has no method 'upload' app.js:46
I am not sure where the cordova_plugins.js gets fetched from. I had read on some forum that it gets generated at run time (I might be wrong).
Does anyone have any idea about what’s going wrong here? I reckon I am missing something on the configuration part. Is it even possible to use ngCordova in a web application since supposedly its meant for mobile development?
Try code below
angular.module('app')
.controller('CordovaCtrl', function($scope, $timeout, $cordovaFileTransfer) {
document.addEventListener("deviceready", function() {
alert("Inside the Cordova Controller - deviceready");
var fileToUpload = "img.png";
var options = {
fileKey : "sendFile",
fileName : "angularJSFileToUpload",
chunkedMode : false,
mimeType : "text/plain"
};
var server = "C:/Dev/Angular file receiver";// Temporary path
var targetPath = "C:/Dev/Angular file sender";// Temporary path
$cordovaFileTransfer.upload(server, targetPath, options)
.then(function(result) {
alert("Success");
}, function(err) {
alert("Error");
}, function(progress){
alert("In Progress");
});
}, false)
});

Ionic http get request (with Ionic) returns html data

I am using Ionic and making http request like this:
$http.get('//GLOBAL.IP/?username=' + username + '&content_type=json')
.then(function (result) {
$scope.days = [];
alert(JSON.stringify(result));
for (first in result.data.weeks) break;
var currentWeek = result.data.weeks[first];
var time = currentWeek.overall.as_time;
$scope.week = currentWeek;
for (day in currentWeek.days.sort().reverse()) {
if (day < 2) {
continue;
}
var currentDay = currentWeek.days[day];
$scope.days.push(currentDay);
if (currentDay.present) {
console.log(parseInt(currentDay.work_time_balance) + parseInt(currentWeek.overall.seconds));
}
}
}, function (result) {
alert(JSON.stringify(result));
$ionicPopup.alert({
title: 'Error',
template: 'Connection failed, try again later!'
});
})
.finally(function () {
// Stop the ion-refresher from spinning
$scope.$broadcast('scroll.refreshComplete');
});
While I am opening app in browser with command ionic serve, everything seems working okay, I've already fixed CORS and other stuff.
But when In mobile app, I am getting this (sorry for not providing plaintext)
UPDATE
$http.get('//GLOBAL.IP/?username=' + username + '&content_type=json')
.then(function (result) {
alert('Good');
}, function (result) {
alert('Bad');
})
This code returns me GOOD, but result.data is still with script tags.
When you are testing this app in working mode what is localhost, Its a local server running on same machine, right.
When you install or run app in your mobile device where it is pointing to? Do you know that, If code is okay then replacing localhost with IP of your machine should resolve this issue.
Many script tags with addRow in ionic http request response, was because of // in the beginning of uri, protocol was selecting successfully in browser, but not in compiled app.

angular-translate with angular-mocks results in blank page

I'm trying to mock a request/response using ngMock and get this error: Unexpected request: GET /locales/en_us.json. After digging around I found this post on how to get around the error. Adding $translateProvider.preferredLanguage('en_us') fixed the error but the templates aren't rendering i.e., I just see a blank page. In the run method I have the following:
$httpBackend.whenGET(env.baseUri + '/1.0/test-data').respond(function(method, url, data){
return [200, [
{
"id": 1,
"name": "test name",7,
"version": "1.0"
}
]]
In the config method:
$translateProvider.preferredLanguage('en_us');
EDIT I fixed this error by adding a passThrough for "locales":
myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
myAppDev.run(function($httpBackend) {
phones = [{name: 'phone1'}, {name: 'phone2'}];
// adds a new phone to the phones array
$httpBackend.whenPOST('/phones').respond(function(method, url, data) {
var phone = angular.fromJson(data);
phones.push(phone);
return [200, phone, {}];
});
$httpBackend.whenGET(/^\/locales\//).passThrough();
});
The fix was to add $httpBackend.whenGET(/^/locales//).passThrough(); see above.

Resources