Post angularjs form to nodejs Express ( Bad request) - angularjs

im new in angularJs, im trying to make a basic login with angularJS and nodejs ( server side), i dont care about security for now im just trying to learn how to post. so i made a login form and a controller with angular :
My Login Form :
<div class="col-md-4">
<h1>Login</h2>
<form class="form" >
<div class="form-group">
<label>Username</label>
<input type="email" class="form-control" ng-model="login.mail" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" ng-model="login.password" required>
</div>
<div>
<button type="text" class="btn btn-default" ng-click="login()">Login</button>
</div>
</form>
</div>
then my router & controller Angularjs :
'use strict';
angular.module('login', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'views/login.html',
controller: 'loginCtrl'
});
}])
.controller('loginCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.login = function() {
$http.post('/api/users/login', $scope.login).success(function (response) {
console.log(response);
// refresh();
});
};
}]);
and Server side i have that :
router.post('/login/', function(req, res) {
// here "/login/" means "/users/login" ( in index of controllers)
console.log(req.body.mail);
var usermail = req.body.mail;
var pass = req.body.password;
console.log(usermail + pass);
User.find({mail: usermail}, function(err, user) {
if (err) {
res.send(err);
console.log("ça marche pas")
} else {
res.json( user );
console.log(user);
}
})
});
server side : it works ( when i use DHC chrome extension to Post) but when im using angularjs view i got that error :
POST http://localhost:3000/api/users/login 400 (Bad Request)
Please help me to solve that, i think i missed something. Thank you in advance.

I think you are sending your login function as in below line:
$http.post('/api/users/login', $scope.login)
You probably want to pass a parameter in your login function that can be sent to server as below:
$scope.login = function(loginData) {
$http.post('/api/users/login', loginData).success(function (response)
Update
You are assigning your form values to $scope.login. If you would create a separate variable for it, for example loginForm, you can send this as valid JSON to your API:
<div class="col-md-4">
<h1>Login</h2>
<form class="form" >
<div class="form-group">
<label>Username</label>
<input type="email" class="form-control" ng-model="loginForm.mail" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" ng-model="loginData.password" required>
</div>
<div>
<button type="text" class="btn btn-default" ng-click="login(loginData)">Login</button>
</div>
</form>
</div>
And .js:
.controller('loginCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.loginForm = {
mail: '',
password: ''
};
$scope.login = function(loginData) {
// Check what this prints out:
console.log(loginData);
$http.post('/api/users/login', loginData).success(function (response) {
console.log(response);
// refresh();
});
};
}]);

Related

Angular - cannot send POST request to log in user and don't know whats wrong?

I am trying to write a post request to log in a user and nothing works. I can't see why and would be happy about any help! Thanks!!
My controller:
'use strict';
app.controller('loginController', function($scope, $state, $http){
$scope.submitLogin=function(email,password)
return $http.post('/login', {email:$scope.email, password:$scope.password })
//since i have ng-model="email"- I don't actually need to pass in $scope.email but can pass in only email ?!
.then(function(success){
if (sucess){
console.log(success)
$state.go('stories')
}
else {
console.log('error')
}
})
.catch(function(err){
console.log("bad")
})
})
Part of the HTML:
<div class="form-group">
<label ng-model="email">email</label>
<input type="text" class="form-control" required />
</div>
<div class="form-group">
<label ng-model="password">password</label>
<input type="password" class="form-control" required />
</div>
<button type="submit" class="btn btn-block btn-primary" ng-click="submitLogin()">login</button>
</form>
State:
'use strict';
app.config(function ($stateProvider) {
$stateProvider.state('login', {
url: '/login',
controller:'loginController',
templateUrl: '/browser/app/login/login.html'
});
});
Put ng-model in input tag.
$scope.submitlogin=function(){
data={
email:$scope.email,
password:$scope.password
}
$http.post('/login',data).success(function(){
});
}
try in this way.It might work.

AngularJS: Only post non-blank values

I am trying to $http.post a JSON object from a form. I can't seem to find the right syntax. Let's assume my form only takes one value (name). I use ng-model to bind the name to an object called modcampaign.name.
What's the correct syntax to post this to a http service?
Further, what if I had another input box, Description, and only want to bind this to modcampaign.description if the user entered data in the input box? If the input box is empty, I'd like to take the value for .description from another object (like modcampaign2.description).
<form ng-submit="modifyCampaign(selCampaign, newName)" class="form-horizontal" name="modCampaign">
<!-- Modify Name -->
<div class="form-group">
<label class="col-lg-2 control-label" for="modName">Name</label>
<div class="col-lg-8">
<input class="form-control" type="text" id="modName" ng-model="modCampaign.name"/>
</div>
</div>
</form>
This is the script file:
var myApp = angular.module('myApp', []);
myApp.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.get('js/campaigns.json').success(function (data) {
$scope.campaigns = data;
});
$http.post('js/campaign_mod.json').success(function (data) {
data = $scope.modCampaign;
});
$scope.selCampaign={};
$scope.selectCampaign = function (campaign) {
$scope.toggleCampaign = !$scope.toggleCampaign;
$scope.selCampaign = campaign;
};
$scope.abbrechen = function () {
$scope.toggleCampaign = !$scope.toggleCampaign;
};
$scope.submit = function () {
$http.post('')
}
}]);
You can include something like this in your controller:
$scope.modCampaign = {};
//this gets called on ng-submit
$scope.submitData = function(){
$http.post("api-end-point", $scope.modCompaign).success(function(data, status) {
//handle response etc.
});
}
Your html will have something like this:
<form ng-submit="submitData()" class="form-horizontal" name="modCampaign">
<!-- Modify Name -->
<div class="form-group">
<label class="col-lg-2 control-label" for="modName">Name</label>
<div class="col-lg-8">
<input class="form-control" type="text" id="modName" ng-model="modCampaign.name"/>
<textarea ng-model="modCampaign.description"/></textarea>
</div>
</div>
</form>
you can use JSON.stringify()
example
$http({
method: "POST",
url: 'http://www.example.com/posturl',
data : JSON.stringify($scope.modcampaign)
}).success(function(response){
console.log(response);
// write any action after post success
})
<form ng-submit="modifyCampaign(modCampaign)" class="form-horizontal" name="modCampaign">
<!-- Modify Name -->
<div class="form-group">
<label class="col-lg-2 control-label" for="modName">Name</label>
<div class="col-lg-8">
<input class="form-control" type="text" id="modName" ng-model="modCampaign.name"/>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="modDescription">Description</label>
<div class="col-lg-8">
<input class="form-control" type="text" id="modDescription" ng-model="modCampaign.description"/>
</div>
</div>
</form>
var myApp = angular.module('myApp', []);
myApp.controller('ListController', ['$scope', '$http', function($scope, $http) {
$scope.modifyCampaign = function(modCampaign) {
console.log(modCampaign)
alert(modCampaign.name) // name:"jane"
alert(modCampaign.description) // description: "hello"
$http.post('js/campaign_mod.json', { name: modCampaign.name, description: modCampaign.description }).success(function (data) {
console.log(data)
});
}
}]);
This method lets you bind all the form value to one object and then you can decode the value in your controller file, below is a link to a working example
http://codepen.io/anon/pen/VjYLvg

AngularJS Login form with ng-click not working

I wrote a basic login form in this plunk http://plnkr.co/edit/xQEN1ZNN5ZEw1CSwNw97?p=preview (click on the red Log into Dashboard button on the Home route).
However for some reason I cannot get the login() method to fire in my loginCtrl controller code.
Why is this example working, and mine is not ? http://plnkr.co/edit/H4SVl6?p=preview
Instead what it's doing is an old-school URL redirect with the user/password parameters passed in as form variables. I can't figure out what's wrong.
Here is LoginCtrl code as well as the login-form.html template :
(function () {
'use strict';
angular.module('routerApp').controller('LoginCtrl',
['$rootScope', '$scope', authenticate]);
function authenticate($rootScope, $scope, userService) {
var login = this;
login.loginUser = function () {
login.dataLoading = true;
//loginService.authUser(login.user, login.password); // TO DO !!!
};
login.test = function () {
var test = true;
};
}
})();
<div ng-show="error" class="alert alert-danger">{{error}}</div>
<form ng-submit="login.loginUser()" name="form">
<div class="form-group">
<label for="username">Username</label>
<i class="fa fa-key"></i>
<input type="text" name="username" id="username" class="form-control" ng-model="login.username" required />
<span ng-show="form.username.$dirty && form.username.$error.required" class="help-block">Username is required</span>
</div>
<div class="form-group">
<label for="password">Password</label>
<i class="fa fa-lock"></i>
<input type="password" name="password" id="password" class="form-control" ng-model="login.password" required />
<span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">Password is required</span>
</div>
<div class="form-actions">
<button type="submit" ng-disabled="form.$invalid || dataLoading" class="btn btn-danger">Login</button>
<img ng-if="login.dataLoading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA=="/>
</div>
</form>
In my local app, it is posting the old-style form variables via the URL, and I cannot get it to fire the login.loginUser function below inside LoginCtrl.
thnk you in advance...
Bob
for some odd reason (perhaps ui-router versioning) the controllerAs is not working.
Diana´s answer is valid, but it doesn´t use the controlleras syntax.
If you still want to use it, change the ui-router setting to:
.state('login', {
url: "/login",
templateUrl: "login-form.html",
controller: 'LoginCtrl as login',
})
That should do the trick ;)
Check it out:
http://plnkr.co/edit/OCqNexVeFFxt4kUuEVc1?p=preview
The controller change I applied is:
angular.module('routerApp').controller('LoginCtrl', function ($rootScope, $scope) {
$scope.loginUser = function () {
$scope.dataLoading = true;
//loginService.authUser(login.user, login.password); // TO DO !!!
};
$scope.test = function () {
var test = true;
};
})
and in the template I removed login. from the ng-if and ng-submit.
Here is a working plunks.

Did Firebase authentication change over night?

I am using Firebase email authentication. It worked pretty well yesterday, but for some reason, it suddenly stopped working this morning, and I have not touched the authentication part in the code at all. I am wondering if there is any changes in Firebase that i am not aware? or I did something may affect it?
Here is the code in controller:
// Home controller
.controller('LoginCtrl', ['$scope', '$firebaseAuth', function($scope, $firebaseAuth) {
// Auth Logic will be here
var firebaseObj = new Firebase("https://xxxx/");
var loginObj = $firebaseAuth(firebaseObj);
$scope.user = {};
$scope.SignIn = function(e){
e.preventDefault(); //To prevent from refresh
var email = $scope.user.username + '#whateverdomain.com';
var password = $scope.user.password;
console.log('Authentication start inside SignIn:' + );
loginObj.$authWithPassword({
email: email,
password: password
})
.then(function(user) {
//Success callback
console.log('Authentication successful');
$location.path('/dashboard');
}, function(error) {
//Failure callback
console.log(error.code);
if(error.code === "INVALID_USER") {
console.log('INVALID_USER');
$scope.loginForm.username.$invalid = true;
}
if(error.code === "INVALID_PASSWORD") {
console.log('INVALID_Password');
$scope.loginForm.password.$invalid = true;
}
});
}
}]);
Here is the view:
<body ng-controller="LoginCtrl">
<div class="container-login">
<div style="padding-bottom:0px; ">
<h1> Login</h1>
</div>
<form class="form-signin" name="loginForm" style="color:#C3BCB6;">
<div class="form-group" ng-class="{'has-error':loginForm.username.$invalid}">
<label>Username</label>
<input ng-model="user.username" type="text" name="username" class="form-control" placeholder="Input your username" ng-minlength="5" ng-maxlength="12"></input>
</div>
<div class="form-group" ng-class="{ 'has-error' : loginForm.password.$invalid }">
<label>Password</label>
<input ng-model="user.password" type="password" name="password" class="form-control" placeholder="Password" ng-minlength="8"></input>
</div>
<button type="button" ng-click="SignIn($event)" ng-disabled="!user.username || !user.password" class="btn btn-lg btn-primary btn-block">Sign in</button>
</form>
</div>
When authentication success, the user is supposed to redirect to the dashboard, or when it failed, it will show error message in the console.
Currently, it only shows "Authentication starts", but no "Authentication success" or any error message, from error.code.
I even checked out previous git commit, the authentication still did not work. Any thoughts? thanks!

firebaseSimpleLogin: $createUser Promise Not Resolving until Another Event Occurs

I'm setting up registration/login functionality using angular, Firebase, and firebaseSimpleLogin. After reading over a few tutorials and another Stack Overflow thread, I've got the registration working with one small but important caveat: the promise on the SimpleLogin $createUser function isn't resolving until I click on a link or button on my html page. Here's my code:
Register.html
<div class="form-group" >
<label class="control-label" for="email">Email</label>
<input class="form-control" type="text" name="email" id="email" ng-model="cred.email"/>
<label class="control-label" for="password">Password</label>
<div class="form-group">
<input class="form-control" type="password" name="password" id="password" ng-model="cred.password"/>
</div>
<div class="form-group">
<input type="submit" value="Register" class="btn btn-primary" ng-click="register()"/>
</div>
</div>
Main.Js
angular.module('myApp')
.controller('AuthCtrl',
['$scope',
'$location',
'$firebase',
'$firebaseSimpleLogin',
'loginService',
function AuthCtrl($scope, $location, $firebase, $firebaseSimpleLogin,
loginService) {
$scope.register = function(){
var user = {
email: $scope.cred.email,
password: $scope.cred.password
};
loginService.register(user);
};
});
loginService.js (note FBURL is defined elsewhere)
angular.module('myApp')
.factory('loginService', function($firebaseSimpleLogin, $rootScope, $location,
$timeout) {
var ref = new Firebase(FBURL);
var auth = $firebaseSimpleLogin(ref);
return {
register: function (user) {
return auth.$createUser(user.email, user.password)
.then(function(registeredUser) {
console.log(registeredUser);
}
)}
});
In the above loginService.js, I'm not seeing the console.log until I click a button or element; however, the user is created in the Firebase Simple Login DB when I look online. As soon as I click a button or element, the console.log shows. My guess as to the issue is that the promise from auth.$createUser() isn't getting resolved, but I cannot find out why that would be.

Resources