Unable to store values in mongoDb? - angularjs

My API log:
OPTIONS /api/signup 204 14.010 ms - -
req.body { '{"name":"rahul jain","mobile":"343453","email":"inayath#cantern.in","password":"123","cpassword":"123"}': '' }
POST /api/signup 200 9.296 ms - 56
I'm making a post request from angular.js to node.js server and here is my angular.js code:
.controller('RegisterCtrl', function($scope, AuthService, $state, $http) {
$scope.user = {
name: '',
mobile:'',
email:'',
password:'',
cpassword:''
};
$scope.signup = function() {
console.log("user",$scope.user);
$http.post("http://localhost:8080/api/signup", $scope.user )
.then(function (response) {
return response;
});
};
})
Here is my node.js code:
apiRoutes.post('/signup', function(req, res) {
console.log("req",req.body);
if (!req.body.name || !req.body.password) {
res.json({success: false, msg: 'Please pass name and password.'});
} else {
var newUser = new User({
name: req.body.name,
mobile: req.body.mobile,
email: req.body.email,
password: req.body.password,
cpassword: req.body.cpassword
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
I think that req.body object having key-value and key is my whole data. Is that correct? Please help me out, thanks in advance.

Related

Retrieve data to put as a parameter when logging in

EDIT:
Including more code because I'm having a hard time implementing your solution.
[...]
$scope.loginForm.loading = false;
$scope.submitLoginForm = function() {
$scope.loginForm.loading = true;
$http
.put('/login', {
email: $scope.loginForm.login,
username: $scope.loginForm.login,
password: $scope.loginForm.password,
_csrf: `here goes the token`
})
.then(function onSuccess() {
window.location = '/myPage';
toastr.success('You are in!', 'Success', { closeButton: true });
})
.catch(function onError(sailsResponse) {
// if (sailsResponse.status === 403) {
// // toastr.error('Removed', 'Error', {
// // closeButton: true
// // });
// window.location = '/restore';
// return;
// }
// Handle known error type(s).
// Invalid username / password combination.
if (sailsResponse.status === 400 || 404) {
// $scope.loginForm.topLevelErrorMessage = 'Invalid email/password combination.';
//
toastr.error(
'Invalid email or username/password combination.',
'Error',
{
closeButton: true
}
);
return;
}
toastr.error(
'An unexpected error occurred, please try again.',
'Error',
{
closeButton: true
}
);
return;
})
.finally(function eitherWay() {
$scope.loginForm.loading = false;
});
};
[...]
[...]
$scope.submitLoginForm = function() {
$http
.put('/login', {
email: $scope.loginForm.login,
username: $scope.loginForm.login,
password: $scope.loginForm.password,
_csrf: `I need the data here`
})
[...]
How do I retrieve the _csrf paramether, reachable through a GET in /csrfToken, at the exact time the request is being send?
Not at the exact time but you can get the csrf_token just before you call '/login'.
$scope.submitLoginForm = function() {
$http.get('/csrfToken')
.then(function successCallback(response) {
var csrf = response.data._csrf;
$http.put('/login', {
email: $scope.loginForm.login,
username: $scope.loginForm.login,
password: $scope.loginForm.password,
_csrf: csrf
});
}, function errorCallback(response) {
alert(response.statusText);
});
}

Ionic: promise goes to error even though it's resolved

I'm building my first ionic app and I have a problem with one of my promises.
The app talks with a REST api to login and register, the login part works but for the register part every time I fill in the form and submit I get the error message, even if the user is created (I can see him in the database of the api) and I can't figure out why, even though the promise is resolved, I still get the error message.
the controller.js code:
wannaPlay.controller('RegisterCtrl', function($scope, AuthService, $ionicPopup, $state) {
$scope.player = {
firstName: '',
lastName: '',
password: '',
email: ''
};
$scope.signup = function() {
AuthService.register($scope.player).then(function(msg) {
$state.go('outside.login');
var alertPopup = $ionicPopup.alert({
title: 'Enregistrement effectué !',
template: msg
});
}, function(errMsg) {
var alertPopup = $ionicPopup.alert({
title: 'Erreur lors de l\'enregistrement !',
template: errMsg
});
});
};
})
the services.js code:
var register = function(player) {
return $q(function(resolve, reject) {
$http.post(API_ENDPOINT.url + '/playersignup', player).then(function(result) {
if (result.data.succes) {
resolve(result.data.msg);
} else {
reject(result.data.msg);
}
});
});
};
Is the REST api really returning a boolean called 'succes', not 'success'?
Maybe it's just that typo. Else you should consider putting logmessages or breakpoints to see what you recieve from the REST backend like this:
console.log(result);
if (result.data.succes) {
console.log("success");
resolve(result.data.msg);
} else {
console.log("error");
reject(result.data.msg);
}

Mongodb CRUD operation with Angularjs and nodejs - How to get message from database if data is already exist?

In controller.js:
angular.module('CRUD').controller('myController',['$scope','$http', function($scope,$http){
$scope.sendData = function(){
console.log($scope.data1);
var formData = {
"username" :$scope.username,
"email" :$scope.email
};
$http({
url:'/formData',
method:'POST',
data:formData
}).success(function(data){
console.log(data);
});
}
}]).directive("myFirstDirective",function(){
return
{
template:"<b>custom directive</b>",
restrict:'E';
}
});
In your nodeJS route API
//User Schema
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: String,
email: {
type: String,
unique: true //means the email has to be unique across all documents
}
});
UserSchema.path('email').validate(function(value, done) {
this.model('User').count({ email: value }, function(err, count) {
if (err) {
return done(err);
}
// If `count` is greater than zero, "invalidate"
done(!count);
});
}, 'Email already exists');
module.exports = mongoose.model('User', UserSchema);
...
//API
app.post('/formData', function(req, res){
User.create(req.body, function(err){
if (!err){
res.send(200); //user created
}
else {
if (err.name === 'ValidationError') res.send(409); //stands for form validation error
else res.send(500);
}
});
});
Good practice to put your requests in the service. For example
angular.module('CRUD').controller('myController',['$scope','$http', 'CRUDService', function($scope,$http, CRUDService){
$scope.sendData = function(){
CRUDService.createUser({
username: $scope.username,
email: $scope.email
}).then(function(res){
//all good user was created
}, function(err){
//error, failed to create user
if (err.status === 409){
//email already exists
}
});
}
}]).service('CRUDService', ['$http', function($http){
this.createUser = function(postData){
return $http.post('/formData', postData);
}
}]);

Initializing AngularJS controller member

I'm trying to create an html/angularjs form that submits data to my webserver. The page is loading the controller because it does execute the submit function. I get an "ReferenceError: formData is not defined" error when I reference formData data. I thought this was the proper way to initialize members of a controller.
var app = angular.module('messagingForm', []);
app.controller('messagingController', function($scope, $http) {
$scope.formData = {
userName: "bob",
email: "bob#bob.com",
subject: "why",
message: "why not?"
};
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(sendContact) {
$scope.submitted = true;
console.log('validating data');
if (sendContact.$valid) {
console.log('sending data');
$http({
method: 'post',
url: 'email.php',
data: {
'name': formData.userName,
'email': formData.email,
'subject': formData.subject,
'message': formData.message
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} //set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
});
} else {
console.log('validating not good');
alert('failed');
}
}
});
I'm unclear how I initialize a member variable I guess. what is the right way to do this?
Matt.
Try with this:
Change:
data: {
'name': formData.userName,
'email': formData.email,
'subject': formData.subject,
'message': formData.message
},
to
data: {
'name': $scope.formData.userName,
'email': $scope.formData.email,
'subject': $scope.formData.subject,
'message': $scope.formData.message
},
Then:
var app = angular.module('messagingForm', []);
app.controller('messagingController', function($scope, $http) {
$scope.formData = {
userName: "bob",
email: "bob#bob.com",
subject: "why",
message: "why not?"
};
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(sendContact) {
$scope.submitted = true;
console.log('validating data');
if (sendContact.$valid) {
console.log('sending data');
$http({
method: 'post',
url: 'email.php',
data: {
'name': $scope.formData.userName,
'email': $scope.formData.email,
'subject': $scope.formData.subject,
'message': $scope.formData.message
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} //set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
});
} else {
console.log('validating not good');
alert('failed');
}
}
});
Because in your code, «formaData» it doesn't exist in the context. You might try also declaring a local variable, something like this:
var formData = {
userName: "bob",
email: "bob#bob.com",
subject: "why",
message: "why not?"
};
Example:
var app = angular.module('messagingForm', []);
app.controller('messagingController', function ($scope, $http) {
var formData = {
userName: "bob",
email: "bob#bob.com",
subject: "why",
message: "why not?"
};
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(sendContact) {
$scope.submitted = true;
console.log('validating data');
if (sendContact.$valid) {
console.log('sending data');
$http({
method : 'post',
url : 'email.php',
data : {
'name': formData.userName,
'email': formData.email,
'subject': formData.subject,
'message': formData.message
},
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
});
} else {
console.log('validating not good');
alert('failed');
}
}
});
You could also create the formData object as a constant and then explicitly pass it in to the controller.
var app = angular.module('messagingForm', []).constant("formData", {
'userName': 'bob',
'email': 'bob#bob.com',
'subject': 'why',
'message': 'why not?'
});
app.controller('messagingController', function($scope, $http, formData) {
Rest of you code here...
It just makes it a little clearer and easier to test.

Angularjs $cookieProvider unknown provider error

I use a custom authentication service to store my authentication token, authToken. This stores the received user profile into a client side cache with $cookieStorage.put() method. When i run, i get the unrecognized provider error:
authToken:
appModule.factory('authToken',['$cookieStorage',
function($cookieStorage) {
var cachedStorage;
return {
setToken: function(token) {
cachedStorage = token;
$cookieStorage.put('userToken', token);
},
getToken: function() {
if (!cachedStorage) {
cachedStorage = $cookieStorage.get('userToken');
}
},
isAuthenticated: function() {
return !!this.getToken();
}
};
}]);
where i use it:
appModule.controller('AuthenticationController',
function ($scope, accountRepository,authToken) {
$scope.login = function(credentials) {
var profile = accountRepository.login(credentials);
profile.success(function(data) {
if (data) {
var userData = {
username: data.username,
firstName: data.firstName,
lastName: data.lastName,
isLogged: true
}
alert('success', 'OK', 'You are now registered' + userData.firstName);
authToken.setToken(userData);
}
});
}
});
the ngCookie module is inserted into appModule, this works fine because i have used it before.
It is $cookieStore not $cookieStorage
https://docs.angularjs.org/api/ngCookies/service/$cookieStore

Resources