not getting any response from router to controller - angularjs

login.controller
angular
.module('app.pages.auth.login')
.controller('LoginController', LoginController);
/** #ngInject */
function LoginController($http, $location)
{
var vm = this;
vm.submitPost = function(userData){
$http({
url: 'http://localhost:7200/api/pages/auth/login',
method: 'POST',
data: userData
}).then(function(res) {
if(res.data.success){
$location.path('/pages/profile');
console.log(res.data.message);
//vm.message=res.data.message;
} else {
//console.log(res.data.message);
//vm.message=res.data.message;
$location.path('/pages/auth/login');
}
}, function(error) {
alert('here');
});
};
}
api.js
router.get('/pages/auth/login', function(req, res) {
console.log(req.flash('loginMessage'));
res.render('auth/login/login.html', { message: req.flash('loginMessage') });
});
router.get('/pages/profile', isLoggedIn, function(req, res) {
return res.json({
success:true,
//message: 'Login Success',
})
res.render('profile/profile.html', {user:req.user });
});
I am not getting any response from router to controller. It shows the alert message 'here'. Is there any thing wrong done here? please help me to fix this.
login.html
<form name="loginForm">
<div class="alertmessage" >{{vm.message}}</div>
<md-input-container flex md-no-float>
<input ng-model="vm.form.username" placeholder="Username" translate
translate-attr-placeholder="LOGIN.USERNAME" name="username" required="true">
<div ng-messages="loginForm.username.$error" ng-show="loginForm.username.$touched">
<div ng-message="required">This field is required</div>
</div>
</md-input-container>
<md-input-container flex md-no-float>
<input ng-model="vm.form.password" type="password" placeholder="Password" translate
translate-attr-placeholder="LOGIN.PASSWORD" name="password" required="true">
<div ng-messages="loginForm.password.$error" ng-show="loginForm.password.$touched">
<div ng-message="required">This field is required</div>
</div>
</md-input-container>
<div class="remember-forgot-password" layout="row" layout-sm="column"
layout-align="space-between center">
<md-checkbox class="remember-me" ng-model="data.cb1" aria-label="Remember Me">
<span translate="LOGIN.REMEMBER_ME">Remember Me</span>
</md-checkbox>
<a ui-sref="app.pages_auth_forgot-password" class="forgot-password md-accent-color"
translate="LOGIN.FORGOT_PASSWORD">Forgot Password?</a>
</div>
<md-button class="md-raised md-accent" aria-label="LOG IN" translate="LOGIN.LOG_IN"
translate-attr-aria-label="LOGIN.LOG_IN"
ng-click="vm.submitPost(vm.form);">
LOG IN
</md-button>
</form>

Please verify what is the value of 'userData' coming from the front end/from where u r calling it. Seems there is an issue with that only!
If thats not the issue then please check the network in developer tools that why your service is failing?
To go to network(on chrome) click F12 >> Network.
Verify your service call and see whats the issue!
EDIT:
where is your 'headers' in service call? You intentionally din't add or you missed it?

This is one more image of network tabWhen i click after login it showed like this
Network tab image showing like this

Related

User cannot login in Angular js with JWT and Node API

I am creating a Node api for user login and am using JSON web Token for authentication.
apiRoutes.put('/login', function(req, res){
User.findOne({name:req.body.name}, function(err, user){
if(err){throw err;}
else{
if(!user){
res.send({success:false, msg:'Auth Failed'});
}else{
user.comparePassword(req.body.password, function(err, isMatch){
if(isMatch && !err){
var token=jwt.encode(user, config.secret);
res.json({success:true, token:'JWT' +token});
}else{
res.send({success:false, msg:'Auth Fails:wrong password'});
}
});
}
}
});
});
Login Controller
app.controller('loginCtrl', function($http, $scope, $location, $cookieStore){
$scope.login=function(){
console.log($scope.loginUser);
$http.put('/api/login', $scope.loginUser).then(function(response){
console.log(response.data.token);
$cookieStore.put('token',response.data.token);
$scope.currentUser=$scope.loginUser.name;
alert("Successfully Loggedin");
}, function(err){
alert('Bad Login Credentials');
});
};
});
Login form HTML
<div class="post" ng-controller="loginCtrl">
<form method="post">
<div class="form-group" >
<label>Name</label>
<input type="text" class="form-control" name="name" ng-model="loginUser.name" />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" ng-model="loginUser.password"/>
</div>
<div class="form-group">
<button class="btn btn-success" ng-click="login()" >Login</button>
</div>
</form>
</div>
The problem is that, when I click on the login button with the user credentials, it is always returning alert("successfully logged in");, despite the user credentials being right or wrong. I think there is something missing in the Angular Login controller, but I am unable to find out the error.
Can someone help me out to find the issue?
Thanks.
When you are sending error response try to send http status code in response. Just try to send
res.send(400, {success:false, msg:'Auth Failed'});

How can I add Firebase Storage to my web app?

I have created a small blog app using angular firebase so that registered user can login and post a blog with article and title. I want to make use of firebase storage so that user can upload images along with the article and title and user can also view the images related to post(store and retrieve feature) in real time.
Here is my html :
<div flex-xs="100" flex-md="80" layout="row" layout-wrap >
<h3 flex="100">Create Post</h3>
<md-input-container flex="40" >
<label>Title</label>
<input ng-model="article.title" type="text" />
</md-input-container>
<md-input-container flex="100" >
<label>Article</label>
<textarea ng-model="article.post" ></textarea>
</md-input-container>
<md-button class="md-raised md-primary" ng-click="AddPost()" ng-disabled="!article.title || !article.post">Publish</md-button>
</div>
Here is my controller :
.controller('AddPostCtrl', ['$scope','$firebase','$firebaseObject', '$firebaseArray', function($scope,$firebase,$firebaseObject,$firebaseArray) {
$scope.AddPost = function() {
var title = $scope.article.title;
var post = $scope.article.post;
var childRef = rootRef.child("Blog-One");
var list = $firebaseArray(childRef);
list.$add({
title: title,
post: post,
}).then(function(childRef) {
console.log(childRef);
}, function(error) {
console.log("Error:", error);
});
}
}])
Can anyone help me with how to implement firebase storage, please? Thanks in advance.
<div flex-xs="100" flex-md="80" layout="row" layout-wrap >
<h3 flex="100">Create Post</h3>
<md-input-container flex="40" >
<label>Title</label>
<input ng-model="article.title" type="text" />
</md-input-container>
<md-input-container flex="100" >
<label>Article</label>
<textarea ng-model="article.post" ></textarea>
</md-input-container>
Add these tags in your html
<progress value="0" max="100" id="uploader"></progress>
<input type="file" value="upload" id="fileButton"><br>
<md-button class="md-raised md-primary" ng-click="AddPost()" ng-disabled="!article.title || !article.post">Publish</md-button>
In your controller
var uploader=document.getElementById('uploader'),
imageUrl,
fileButton=document.getElementById('fileButton');
fileButton.addEventListener('change', function(e) {
var file=e.target.files[0];
var storageRef=firebase.storage().ref('firebase').child(file.name);
var task=storageRef.put(file);
task.on('state_changed',
function progress(snapshot){
var percentage=( snapshot.bytesTransferred / snapshot.totalBytes )*100;
uploader.value=percentage;
if (percentage==100){
storageRef.getDownloadURL().then(function(url) {
Here you will get download url
imageUrl=url;
});
}).catch(function(error) {
// Uh-oh, an error occurred!
});
}
},
function error(err){
},
function complete(){
}
);
});
So you can allow all the users to post the article with an image. But keep one thing wait until the image uploaded in the storage, and then show the publish article button. To do that wait until the progress bar to get 100% then show the publish article button

Post angularjs form to nodejs Express ( Bad request)

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();
});
};
}]);

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!

Unable to pass Stripe token to backend using Angular and Node

I am trying to process a Stripe charge in Angular using the Angular Payments module. I am able to get the token from Stripe, but receive the following error on the client side when I attempt to submit the token to my Express server:
ReferenceError: token is not defined
Any thoughts on how to resolve this?
Here's the relevant code:
Controller:
myApp.controller('PaymentFormCtrl',
function($scope){
$scope.handleStripe = function(status, response){
console.log('response', status, response);
if(response.error) {
console.log('error');// there was an error. Fix it.
} else {
console.log('no error');
token = response.id;
return $http.post('http://localhost:8080/api/payments', payment);
}
};
});
HTML for form:
<form stripe-form="handleStripe" name="myForm">
<div class="span3">
<label for="">Card number</label>
<input type="text" class="input-block-level" ng-model="number" payments-validate="card" payments-format="card" payments-type-model="type" ng-class="myForm.number.$card.type"/>
</div>
<div class="span1">
<label for="">Expiry</label>
<input type="text" class="input-block-level" ng-model="expiry" payments-validate="expiry" payments-format="expiry" />
</div>
<div class="span3">
<label for="">Name on card </label>
<input type="text" class="input-block-level">
</div>
<div class="span1">
<label for="">CVC</label>
<input type="text" class="input-block-level" ng-model="cvc" payments-validate="cvc" payments-format="cvc" payments-type-model="type"/>
</div>
<div class="span4">
<button type="submit" class="btn btn-primary btn-large">Submit</button>
</div>
</form>
Server Javascript:
apiRouter.route('/payments')
.post(function(req, res) {
var stripeToken = request.body.stripeToken;
var charge = stripe.charges.create({
amount: 1000,
currency: "usd",
source: stripeToken,
description: "payinguser#example.com"
}, function (err, charge) {
if (err && err.type === 'StripeCardError') {
}
});
});
One thing to fix for sure is that in the server side your request is 'req' yet you are trying to get the token from
request.body.stripeToken,
should be
req.body.stripeToken

Resources