res.json sending old data - angularjs

Hi I have an issue that I can't really explain with res.json from express.
Here is my /login route:
router.post('/login', function (req, res) {
if (req.body.user) {
var newUser = (typeof req.body.user === 'string') ? JSON.parse(req.body.user) : req.body.user;
User.findOne({ email: newUser.email })
.exec(function (err, user) {
if (err) {
return res.json({ error: true, data: err });
} else {
if (user !== undefined && user !== null) {
// Check password and generate a token if it exist
encrypt.checkHash(newUser.pwd, user.pwd, function (err, isCorrect) {
if (err) {
return res.json({ error: true, data: err });
} else {
if (isCorrect != false) {
// Generate token and send it
Token.generateToken({
_id: user._id, email: user.email,
iat: moment().valueOf(),
exp: moment().add(30, 'minutes').valueOf(),
},
conf.secret,
{},
function (err, token) {
if (err) {
return res.json({ error: true, authenticate: false, data: err });
} else {
console.log('Logged');
return res.json({
error: false,
token: token,
authenticate: true,
msg: 'user_connected',
});
}
});
} else {
console.log('Not logged');
return res.json({ error: true, authenticate: false, msg: 'user_undefined' });
}
}
});
} else {
return res.json({ error: true, authenticate: false, msg: 'user_undefined' });
}
}
});
} else {
return res.json({ error: true, authenticate: false, msg: 'user_empty' });
}
});
And here the function where I made my request to that route:
userRequest.auth = function (user) {
console.log('AUTH userRequest ', user);
$http({
method: 'POST',
url: url + '/auth/login',
dataType: 'application/json',
data: { user: user },
}).then(function successCallback(response) {
$log.warn('user request', response);
deferred.resolve(response);
}, function errorCallback(err) {
deferred.reject(err);
});
return deferred.promise;
};
And here my onClick function which start the process
var promise = userRequest.auth($scope.user);
promise.then(function (response) {
var data = response.data;
$log.info('Login RESPONSE ', response);
if (data.error == false && data.authenticate == true) {
$log.info('You are logged');
$scope.notification = setAlertBoxOptions($scope.notification, true, 'alert-success', 'Vous ĂȘtes maintenant connectĂ©');
} else {
$log.info('Wrong informations');
$scope.notification = setAlertBoxOptions($scope.notification, true, 'alert-danger', 'Utilisateur inconnue');
}
}, function (reason) {
$log.error(reason);
});
My function's encrypt.checkHash callback work and the value isCorrect is the good one when checking my password hash. It log 'Logged' if the password is correct and 'Not logged' if it's not.
The first time I made a request on this route it send me back an response by res.json and I get the expected data.
But after the first request, the data I receive is always the one I received on the first query.
e.g: The first time I send correct identification info and it return me
{error: false, token: token, authenticate: true, msg: 'user_connected'}
but after that, every time I try to make another query on that route I keep receiving this JSON object event if my identification info are false.
I'm not an expert in Nodejs and I tried to replace all my
res.json({...})
by
return res.json({...})
to stop the execution but the result still the same.
Can you share your wisdom with me and help me solve this case please ?

I found out why it was happening, in my angularJS factory I initialize only once the $q service and where using it inside a method of the factory. like this:
angular.module('myApp').factory(
'userRequest',
['$log', '$q',
function ($log, $q) {
// Initialized wrongly
var deferred = $q.defer();
userRequest.auth = function (user) {
console.log('AUTH userRequest ', user);
$http({
method: 'POST',
url: url + '/auth/login',
dataType: 'application/json',
data: { user: user },
}).then(function successCallback(response) {
$log.warn('user request', response);
deferred.resolve(response);
}, function errorCallback(err) {
deferred.reject(err);
});
return deferred.promise;
};
}])
instead of:
angular.module('myApp').factory(
'userRequest',
['$log', '$q',
function ($log, $q) {
userRequest.auth = function (user) {
// Where to initialize it
var deferred = $q.defer();
console.log('AUTH userRequest ', user);
$http({
method: 'POST',
url: url + '/auth/login',
dataType: 'application/json',
data: { user: user },
}).then(function successCallback(response) {
$log.warn('user request', response);
deferred.resolve(response);
}, function errorCallback(err) {
deferred.reject(err);
});
return deferred.promise;
};
}])

Related

Passing $scope through AJAX, but only few variables inserted

I am trying to pass a variable through AJAX to an API. Here is the angular controller:
$scope.register = function() {
_.each($scope.photos, function(images) {
$upload.upload({
url: '/api/indorelawan/timaksibaik/register/upload-images',
method: 'POST',
data: {},
file: images
})
.success(function(data) {
$scope.team.photos.push(data.result.path);
})
});
$http({
method : 'POST',
url : '/api/indorelawan/timaksibaik/register',
data : $.param($scope.team),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data) {
if (!data.success) {
...
}
else {
...
}
});
}
I tried console.log the $scope.team.photos before it calls the /register API. It displays the data perfectly. But when /register API is runned, the $scope.team.photos is not included. Here is the API:
/*Register Tim Aksi Baik*/
apiRouter.post('/timaksibaik/register', function(req, res) {
// TODO: Create new value to access general statistics data, e.g.: response time.
console.log(req.body);
var team = new GoodActionTeam();
_.each(req.body, function(v, k) {
team[k] = v;
});
team.created = new Date();
team.save(function(err, data) {
if (err) {
res.status(500).json({
success: false,
message: "Gagal menyimpan data organisasi baru.",
system_error: "Error while saving organization data: " + err.message
});
}
else {
res.status(200).json({
success: true,
message: "Organisasi Berhasil Dibuat",
result: data
});
}
});
});
The output of the req.body is only:
{ logo: '/uploads/user_avatar/register/2018-1-14_18:18:3.png',
name: 'ererr',
url_string: 'ererr',
description: 'dfdfd',
focuses: [ '549789127e6a6e2c691a1fc0', '549789127e6a6e2c691a1fc0' ] }
It looks like the $scope.team.photos is not included when the data is passed to the API. What went wrong?
The $upload.upload() is async and by the time you make a post with $scope.team there is no guarantee that all the upload success callbacks have been completed

similar post req giving response in postman but not on angular $http.post

There is post request to get token for user . I have used angular $http.post method In my browser network window its not giving me response but when i try this in postman it gives me response here is screen shot attached
please help
this.login = function (loginData) {
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;
//if (loginData.rememberMe) {
data = data + "&client_id=" + constants.AUTHSETTINGS.CLIENT_ID;
//}
debugger;
console.log(data)
var deferred = $q.defer();
$http.post(api_url + '/token', data, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.then
(function (response) {
if (loginData.rememberMe) {
localStorageService.set('authorizationData', { token: response.data.access_token, userName: loginData.userName, refreshToken: response.data.refresh_token, useRefreshTokens: true });
}
else {
localStorageService.set('authorizationData', { token: response.data.access_token, userName: loginData.userName, refreshToken: "", useRefreshTokens: false });
}
console.log('---auth servcie')
console.log(response)
authentication.isAuth = true;
authentication.userName = loginData.userName;
authentication.useRefreshTokens = loginData.rememberMe;
deferred.resolve(response);
}
,function (err, status) {
console.log('auth error -- here ')
console.log(err)
console.log(status)
deferred.reject(err);
//deferred.resolve(err);
});
return deferred.promise;
};
raw data
var data = "grant_type=password&username=asad#gmail.com&password=1234&client_id=angularjs

ngResource: Angularjs - Send post request with headers and request body

I am trying to send a post request with both a header and request body. So far I have reached this point:
createJob: function(jobName, jobAddress, jobContact, jobComments) {
var payload = {
name: jobName,
address: jobAddress,
contact: jobContact,
comments: jobComments
};
console.log(payload);
return $resource(route, {}, {
save: {
method: 'POST',
header: {'Content-Type': 'application/json'},
transformRequest: function(data){
console.log('Data in transform request is');
console.log(data);
return data; // this will go in the body request
}
}
});
}
I am not sure where to place the payload in this case, any help? Also when making the call, I am currently trying to do something like:
createJob(this.jobName, this.jobAddress, this.jobContact, this.jobComments).
save().$promise.
then(function (response) {
console.log('Create job response is');
console.log(response);
}).
catch(function (error) {
console.log('Create job error is');
console.log(error);
});
Any help would be appreciated!
I came to a solution for anyone that is interested:
createJob: function(jobName, jobAddress, jobContact, jobComments) {
var payload = {
name: jobName,
address: jobAddress,
contact: jobContact,
comments: jobComments
};
console.log(payload);
return $resource(route, {}, {
save: {
method: 'POST',
transformRequest: function(data){
console.log('Data in transform request is');
console.log(data);
return angular.toJson(data); // this will go in the body request
}
}
}).save({}, payload);
}
createJob(this.jobName, this.jobAddress, this.jobContact, this.jobComments).$promise.
then(function (response) {
console.log('Create job response is');
console.log(response);
//Refresh the page so newly created job can be seen
window.location.reload();
}).
catch(function (error) {
console.log('Create job error is');
console.log(error);
});

ngResource return success callback result by service

I have recetly began an adventure with AngularJs but idea of promises and returning asynchonous data overhelmed me.
I am trying to accomplish simple data returining via .factory method and $resource service.
Here is my $resource service returning promise
(function () {
angular.module('token')
.factory('tokenService', ['$resource', 'baseUri', tokenService]);
function tokenService($resource, baseUri) {
return $resource(baseUri + 'token', {}, {
post: {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
});
}
})();
I am using this service in another service which should returns data.
(function () {
angular.module('authorization')
.factory('authorizationService', ['$httpParamSerializer', 'tokenService', authorizationService]);
function authorizationService($httpParamSerializer, tokenService) {
return {
authorization: function(user){
var token = {};
tokenService.post({}, $httpParamSerializer({
grant_type: 'password',
username: user.login,
password: user.password,
client_id: user.clientId
}), function(response){
token = response;
console.log('authorizationResponse', response);
console.log('authorizationToken', token);
});
// .$promise.then(function(response){
// token = response;
// console.log('authorizationResponse', response);
// console.log('authorizationToken', token);
// });
console.log('finalToken', token);
return token;
}
};
}
})();
But i cannot force token variable to posses tokenService.post() result before returing.
First: inject $q in your authorizationService.
Try this:
authorization: function(user) {
return $q(function(resolve, reject) {
tokenService.post({}, {
grant_type: 'password',
username: user.login,
password: user.password,
client_id: user.clientId
})
.$promise
.then(function(token) {
resolve(token);
})
.catch(function(err) {
reject(err);
});
});
}
Then, in your controller, you can use:
authorizationService.authorization(user)
.then(function(token) {
// Some code here
})
.catch(function(err) {
// Handle error here
});

loginCtrl is not correct hence unable to use auth0 with ionic

I am trying to develop an ionic app using auth0 authentication and I followed these instructions. Once I add the loginCtrl it returns an error.
Error
[ng:areq] Argument 'loginCtrl>' is not a function got undefined or TypeError: Cannot read property 'parseOptions' of undefined
Controller.js File
angular.module('comicsApp')
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.controller('contactsController', function(contfact, $scope, $ionicLoading) {
var _this = this;
$scope.$on('$ionicView.enter', function(){
$ionicLoading.show();
contfact.getContacts().then(function(response){
_this.contactitem = response.data;
}).catch(function(response){
//request was not successful
//handle the error
}).finally(function(){
$ionicLoading.hide();
});
});
})
.controller('iPController',function ($scope,$http) {
$http.get("http://localhost:9510/api/profiles/Getprofile")
.success(function(response) {$scope.ipInfo = response;})
.error(function(response) {
$scope.message="Error";
})
})
.controller('contactdtl-Controller',function ($scope,$http,$stateParams) {
$http.get("http://localhost:9510/api/contacts/usercontacts/",{params: { "id": $stateParams.id }
})
.success(function(response) {$scope.contactdtlinfo = response;})
.error(function(response) {
$scope.message="Error";
})
})
.controller('addcontact',function ($scope,$http,$stateParams) {
$scope.save = function () {
if (this.lastname != "123") {
$http({
method: 'POST',
contentType: 'application/json; charset=utf-8',
// data: JSON.stringify(this.contact),
url: 'http://localhost:9510/api/contacts/Postcontacts',
data: ({"owner":this.owner,"fisrtname":this.fisrtname,"lastname":this.lastname,"mobile":this.mobile,"email":this.email,"relation":this.relation,"home":this.home,"office":this.home})
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
// $scope.productsData.push(response.data);
// $scope.clear();
alert("Product Added Successfully !!!");
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
alert("Error : " + response.data.ExceptionMessage);
});
}
else {
alert('Please Enter All the Values !!');
}
};
})
.controller('heartattack',function ($scope,$http, $ionicPopup,$state,$ionicPlatform, $cordovaGeolocation) {
$scope.showConfirm = function($scope) {
/////////////////////////////////////////get coordinates //////////////////////////////////////////
///////////////////////////////////////get coordinates /////////////////////////////////////////////
var confirmPopup = $ionicPopup.confirm({
title: 'Confirm Heartattack',
template: 'ARE YOU SURE THAT YOU WANT TO RECORED YOUR CASE ?'
});
confirmPopup.then(function(res,$scope) {
if(res) {
$scope.date = new Date().toLocaleDateString('en-GB');
$scope.time = new Date().toLocaleTimeString('en-GB');
$http({
method: 'POST',
contentType: 'application/json; charset=utf-8',
// data: JSON.stringify(this.contact),
url: 'http://localhost:9510/api/reports/Postreport',
data: ({
"id": 1,
"type": "heartattack",
"coordinates": '$essam',
"location": "adfasdfas",
"injuries": 1,
"time": $scope.time,
"date": $scope.date,
"details": "having heart attack",
"owner": 232
})
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
// $scope.productsData.push(response.data);
// $scope.clear();
// alert("Product Added Successfully !!!");
$state.go('heartattack');
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
alert("Error : " + response.data.ExceptionMessage);
});
} else {
}
});
};
})
.controller('addreport',function ($scope,$http,$stateParams) {
$scope.save = function () {
$scope.date = new Date().toLocaleDateString('en-GB');
$scope.time = new Date().toLocaleTimeString('en-GB');
$scope.test=this.type;
alert($scope.test);
$http({
method: 'POST',
contentType: 'application/json; charset=utf-8',
// data: JSON.stringify(this.contact),
url: 'http://localhost:9510/api/reports/Postreport',
data: ({
"id": 1,
"type": this.type,
"coordinates": "asasdfasddfasdf",
"location": this.location,
"injuries": this.injuries,
"time": $scope.time ,
"date": $scope.date,
"details": this.details,
"owner": 232
})
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
// $scope.productsData.push(response.data);
// $scope.clear();
alert("Report Added Successfully !!!");
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
alert("Error : " + response.data.ExceptionMessage);
});
};
})
.controller('LoginController',function LoginController ($scope, $state, auth, store){
var vm = this;
function doLogin() {
auth.signin({
container: 'lock-container',
authParams: {
scope: 'openid offline_access',
device: 'Mobile device'
}
}, function (profile, token, accessToken, state, refreshToken) {
// Success callback
store.set('profile', profile);
store.set('token', token);
store.set('accessToken', accessToken);
store.set('refreshToken', refreshToken);
$state.go("home");
}, function () {
// Error callback
});
}
doLogin();
});
.controller('watchme',function ($scope,$timeout,$cordovaFlashlight,$cordovaSms,$ionicPlatform) {
$scope.myTimer={};
$scope.myTimer.value=5;
$scope.myTimerFixed=5;
$scope.myTimer.startBtn=false;
$scope.myTimer.stopBtn=true;
var svg=document.getElementsByClassName('round-progress')[0];
svg.onload=function() {
$scope.radius=svg.getBoundingClientRect().width/2;
}
var myTimerVariable;
$scope.myCustomtTime = function() {
$scope.myTimer.value--;
if($scope.myTimer.value==0){
$timeout.cancel(myTimerVariable);
complete(false);
return false;
}
myTimerVariable=$timeout($scope.myCustomtTime, 1000);
}
$scope.start=function(){
$scope.myTimer.startBtn=true;
$scope.myTimer.stopBtn=false;
myTimerVariable=$timeout($scope.myCustomtTime, 1000);
};
$scope.stop=function(){
complete(true);
$timeout.cancel(myTimerVariable);
};
var complete= function(forceFullAbort){
if(forceFullAbort){
alert('you killed the timer');
$cordovaFlashlight.switchOff()
.then(
function (success) { /* success */ },
function (error) { /* error */ });
}
else
{
alert('time completed');
// $cordovaFlashlight.switchOn()
// .then(
// function (success) { /* success */ },
// function (error) { /* error */ });
// $cordovaSms.send('66549815', 'help me').then(function(){
// alert("SMS enviado com sucesso");
// }, function(err){
// alert('Erro ao enviar SMS');
// });
var number = 66549815;
var onSuccess=function(number){
alert("invia messaggio");
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
window.plugins.CallNumber.callNumber(onSuccess, onError, number);
}
$scope.myTimer.startBtn=false;
$scope.myTimer.stopBtn=true;
};
$scope.getStyle = function(){
var transform = ($scope.isSemi ? '' : 'translateY(-50%) ') + 'translateX(-50%)';
return {
'top':'50%',
'bottom': 'auto',
'left': '50%',
'transform': transform,
'-moz-transform': transform,
'-webkit-transform': transform,
'font-size': $scope.radius/3.5 + 'px'
};
};
})
;
Might be completely off the ball here but looking at your code I cannot see a "loginCtrl" but a "logincontroller". Is this a typo on your question or is your html trying to call loginCtrl ?

Resources