'AWS is not defined' when using aws-sdk-js in angular - angularjs

Following this tutorial, implementing the AWS sdk with angular, I'm getting AWS is not defined from jshint (using grunt to serve the app).
I've installed the sdk with bower install aws-sdk-js --save, and it correctly appears in my index.html file.
This is my controller:
angular.module('myApp')
.controller('S3uploadCtrl', function ($scope) {
console.log(AWS);
$scope.creds = {
bucket: 'myBucket',
accessKey: 'accKey',
secretKey: 'secKey'
};
$scope.upload = function() {
// Configure The S3 Object
AWS.config.update({ accessKeyId: $scope.creds.accessKey, secretAccessKey: $scope.creds.secretKey });
AWS.config.region = 'us-west-2';
var bucket = new AWS.S3({ params: { Bucket: $scope.creds.bucket } });
if($scope.file) {
var params = { Key: $scope.file.name, ContentType: $scope.file.type, Body: $scope.file, ServerSideEncryption: 'AES256' };
bucket.putObject(params, function(err, data) {
if(err) {
// There Was An Error With Your S3 Config
alert(err.message);
return false;
}
else {
// Success!
alert('Upload Done');
}
})
.on('httpUploadProgress',function(progress) {
// Log Progress Information
console.log(Math.round(progress.loaded / progress.total * 100) + '% done');
});
}
else {
// No File Selected
alert('No File Selected');
}
};
function alert(msg) {
console.alert(msg);
}
});
There isn't much about this on google. I found one other SO question which I've tried to follow to no avail. (changed the order of my <script> tags etc.)

It's a JSHint error. JSHint makes sure you're accessing defined variables, and has no idea that an AWS global variable exists et runtime. So you need to tell JSHint that this globa variable exists and that you allow your code to access this global variable (although you probably should hide it behind an angular service, to make your code testable).
Edit your .jshintrc file (it might have another name: check your build configuration), and add (or modify) the following rule:
"globals": { "AWS" : false }

If you are just getting a JSHint error, it might be because AWS is not recognised as a variable. Create a .jshintrc file in the root of your project, and put this config in it:
"globals": {
"AWS": false
}

'AWS is not defined' this error occurs when you forgot to define js ,
After "bower install aws-sdk-js"
you need to define "aws-sdk.min.js" and "aws-sdk.js" to your index.html in script tag like
<script src="bower_components/aws-sdk/dist/aws-sdk.min.js"></script>
<script src="bower_components/aws-sdk/dist/aws-sdk.js"></script>

Related

How to serve two AngularJS apps with one Express server?

I've searched all around and i've found a few ways of how to do this, but none seem to specifically fit my needs and i can't get them to work. My latest attempt is below, using express-subdomain with express and trying to server two separate AngularJS apps based on the incoming sub domain. This code currently seems to serve the correct app, but none of the Angular modules are included from what i can see. The browser console has many many errors of 'Uncaught SyntaxError: Unexpected token <'. Which from previous experience i believe means AngularJS was not loaded correctly. Keep in mind, i have no issue running only one AngularJS app, it is only when i try to bring in sub-domain and serve that second static app.
I've already tried vhost with similar failed results.
server.js
app.use(subdomain('app1',express.static(__dirname + '/public/app1')));
app.use(subdomain('app2',express.static(__dirname + '/public/app2')));
require('./app/routes')(app); // configure our routes
app.listen(port);
routes.js
app.get('*', function(req, res) {
var firstIndex = req.get('host').indexOf('.');
var subdomain = req.get('host').substr(0,firstIndex).toLowerCase();
if (subdomain === 'app1'){
res.sendFile(root + '/public/app1/views/index.html');
}else if (subdomain === 'app2'){
res.sendFile(root + '/public/app2/views/index.html');
}else{
res.sendFile(root + '/public/app1/views/notfound.html');
}
});
if (subdomain === 'app1'){
res.sendFile(root + '/public/app1/views/index.html');
This seems wrong.
This will send index.html to any request, i.e. request for js file.
Should be i.e.:
if (subdomain === 'app1' && req.url.indexOf('.') === -1){
} else if (subdomain === 'app2' && req.url.indexOf('.') === -1){
} else { /* return static asset */ }
...
If you create a general json whit diferent instance whit the diferents aplicacitions and create all the call, you can emulate this. This is the example:
const routes = {
routeApp1: {
appTest1:{
url: '/appTest1/appTest1',
file: './mock/appTest1.json',
},
appTest2:{
url: '/appTest1/appTest2',
file: './mock/appTest2.json',
},
}
routeApp2: {
appTest1:{
url: '/appTest2/appTest1',
file: './mock/appTest1.json',
},
appTest2:{
url: '/appTest2/appTest2',
file: './mock/appTest2.json',
},
}
};
app.get(routes.routeApp1.appTest1.url, (req, res) => {
res.send(JSON.stringify(require(routes.routeApp1.appTest1.file)));
});
app.get(routes.routeApp2.appTest2.url, (req, res) => {
res.send(JSON.stringify(require(routes.routeApp2.appTest2.file)));
});
app.listen(3000, () => {
console.log(`Mocks app listening on port ${port}!`);
});

Adding google plus login to ionic app

I am trying to add google plus login to my ionic app.
Following this link gives me an error.
https://ionicthemes.com/tutorials/about/google-plus-login-with-ionic-framework
Error is : cannot read property googleplus of undefined.
Here is my app.js:
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
Steps to Configure authentication in Device(android)
ionic start newApp
ionic platform add android
cordova plugin add cordova-plugin-inappbrowser
bower install ngCordova
bower install ng-cordova-oauth -S
include both script into index.html above cordova.js
<script src="lib/ngCordova/dist/ng-cordova.min.js"></script>
<script src="lib/ng-cordova-oauth/dist/ng-cordova-oauth.js"></script>
<script src="cordova.js"></script>
Dependency injection
include below code
$scope.googleLogin = function() {
console.log('In My Method');
$cordovaOauth.google("Client ID", ["https://www.googleapis.com/auth/urlshortener", "https://www.googleapis.com/auth/userinfo.email"]).then(function(result) {
console.log(JSON.stringify(result));
// results
}, function(error) {
// error
console.log('In Error');
console.log(error);
});
}
add button to view file and call the function
1 first add inappbrower in your app
2 create app id for google console
https://console.developers.google.com
a: create new project
b: click on Credentials
c: choose web application
d: set redirect path
if u have if not than set http://localhost/callback
e: click on create button
than a pop up appear save those id
after that add following code
NOTE:Please change your app id and secret id in code
$scope.loginGoogle = function() {
var requestToken = '';
var accessToken = '';
var clientId = '1018908884240-futc1bfc681kl2jegi3a7nn1m28aem1o.apps.googleusercontent.com';
var clientSecret = 'KRQGDwu_llvagUucKM9oLZ7I';
var deferred = $q.defer();
$cordovaOauth.google(clientId, ['email']).then(function(result) {
$localStorage.accessToken = result.access_token;
deferred.resolve(result.access_token);
$http.get('https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + $localStorage.accessToken, {
params: {
format: 'json'
}
}).then(function(result) {
console.log(JSON.stringify(result));
var id =result.data.id;
deferred.resolve(result.data);
}, function(error) {
deferred.reject({
message: 'here was a problem getting your profile',
response: error
});
});
}, function(error) {
deferred.reject({
message: 'There was a problem signing in',
response: error
});
});
}
Try to add <script src="cordova.js"></script> to your index.html file.
And Cordova plugins only runs on emulators or real devices. try Ripple Emulator if you want to test it in a browser.
Credit to Cordova plugins not working with ionic

Electron: how to execute AngularJS in Electron without CSRF protection?

Recently I started working on my first electron app and and bumped into a problem, hope someone may be able to help me out.
I would like to use Electron to quickly create a cool looking app by using a Admin Backend AngluarJS HTML theme.
The AngluarJS theme works fine from a http:// source but not when I load the theme from a local drive like the C:\ drive, it breaks the theme because (I think) of CSRF protection policies in chrome.
Now I googled my ass off but I can't find a good solution. I thought that running a http-server in electron might be a solution so I tried the npm http-server package. Problem with this approach is that the nodejs code is not working anymore in this case beceause the http-server will only proces static files.
Is there maybe another solution?
Thanks for thinking with me!
Electron has no problem running an AngularJs app.
I have built a few Electron apps using Angular with no CSRF problems.
One way to get around this is to create a simple server running inside electron, like shown below:
// <YOUR-ENTRY-FILE>.js
app.on('ready', function() {
mainWindow = new BrowserWindow({
width: 800,
height: 600
});
var server = http.createServer(requestHandler).listen(9527);
mainWindow.loadUrl('http://localhost:9527/index.html');
mainWindow.webContents.on('did-finish-load', function() {
mainWindow.setTitle(app.getName());
});
mainWindow.on('closed', function() {
mainWindow = null;
server.close();
});
});
function requestHandler(req, res) {
var
file = req.url == '/' ? '/index.html' : req.url,
root = __dirname + '/www',
page404 = root + '/404.html';
getFile((root + file), res, page404);
};
function getFile(filePath, res, page404) {
fs.exists(filePath, function(exists) {
if(exists) {
fs.readFile(filePath, function(err, contents) {
if(!err) {
res.end(contents);
} else {
console.dir(err);
}
});
} else {
fs.readFile(page404, function(err, contents) {
if(!err) {
res.writeHead(404, {'Content-Type': 'text/html'});
res.end(contents);
} else {
console.dir(err);
}
});
}
});
};
There really should not be a need for you to do this, check your paths and have this as the last option.
quite late, but i found a solution to this, maybe this helps someone someday https://stackoverflow.com/a/60452312/1284216

How to listen to socket emit on sails.io.js?

I'm using Sails 0.11 in my back-end, and angularjs in the front-end.
I have a TwitterController in sails with the following code, to open a stream with the Twitter Streaming API (this uses the node module twit):
var Twit = require('twit');
var T = new Twit(sails.config.twit);
var stream = T.stream('statuses/filter', {
track: ['apple']
});
module.exports = {
open: function(req, res) {
if (!req.isSocket) {
return res.badRequest();
}
var socketId = sails.sockets.id(req.socket);
stream.start();
stream.on('tweet', function(tweet) {
sails.log.debug('Tweet received.');
sails.sockets.emit(socketId, 'tweet', tweet);
});
}
};
In my front-end (with the angular-sails module):
$sails.get('/twitter/open').then(function(resp) {
console.log(resp.status);
}, function(resp) {
alert('Houston, we got a problem!');
});
This of course reaches my back-end controller, and the streaming starts, but how do I listen to the
sails.sockets.emit(socketId, 'tweet', tweet);
issued by the server?.
I'd appreciate any help here!.
Sails library creates a global variable "io", so you can use also:
io.socket.on("tweet", function(data){})
Following wZVanG's answer. This is how I did it, using the angular-sails angular module.
$sails.get('/twitter/open').then(function(resp) {
console.log(resp.status);
}, function(resp) {
alert('Houston, we got a problem!');
});
$sails.on('tweet', function(message) {
console.log(message);
});
That logs every tweet received to the browser's console.

Cordova FileTransfer: upload image to AWS s3

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.

Resources