angularjs form post http interceptor not working - angularjs

i am new to angularjs so pardon my ignorance. Here is the interceptor i have for my angularjs app
.config(function ($routeProvider, $locationProvider, $httpProvider) {
$routeProvider
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
$httpProvider.interceptors.push('authInterceptor');
})
.factory('authInterceptor', function ($rootScope, $q, $cookieStore, $location) {
return {
// Add authorization token to headers
request: function (config) {
config.headers = config.headers || {};
if ($cookieStore.get('token')) {
config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
}
return config;
},
// Intercept 401s and redirect you to login
responseError: function(response) {
if(response.status === 401) {
$location.path('/login');
// remove any stale tokens
$cookieStore.remove('token');
return $q.reject(response);
}
else {
return $q.reject(response);
}
}
};
})
I have an html which posts the data to the server
<form role="form" id="addTeacherForm" data-validate="parsley" action="/api/v1/teacher" method="post">
<h4>Add your Teacher's data</h4>
<div class="form-group">
<div class="row">
<div class="col-xs-12 col-sm-5 col-md-5">
<input type="text" ng-model="teacher.name" name="name" class="form-control input-md"
placeholder="Name" required="required">
</div>
<div class="col-xs-12 col-sm-5 col-md-5">
<input type="date" ng-model="teacher.dob" name="dob" class="form-control input-md"
placeholder="Date Of Birth" required="required">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-xs-12 col-sm-5 col-md-5">
<div class="input-icon"><i class="icon-user"></i>
Teacher's Photo
<input type="file" id="teacherPhoto" name="teacherPhoto" accept="image/*" required="required">
</div>
</div>
<div class="col-xs-12 col-sm-5 col-md-5">
<div class="form-group">
<input type="text" name="phoneNumber" ng-model="teacher.phoneNumber"
class="form-control input-md" name="phoneNumber"
placeholder="Phone Number(Optional)">
</div>
</div>
</div>
</div>
<div class="form-actions text-center">
<div class="col-xs-12 col-sm-5 col-md-5">
<input type="submit" value="Submit" class="btn btn-primary btn-block btn-md">
</div>
</div>
</form>
Now when i press submit on this form the request goes to the server but the interceptor doesn't get invoked and the request fails because the headers are not populated with the authorization token. Any idea why this is not being intercepted?

Related

Controller is not working for the bellow code?

controller.js code
angular.module('Zoho.controllers', [])
.controller('loginController', function($scope, $state) {
$scope.login = function(loginData) {
console.log(loginData);
}})
.controller('signUpController', function($scope, $state) {
$scope.signUp = function(signUpData) {
console.log(signUpData);
}})
app.js
angular.module('Zoho',
['ui.router','Zoho.controllers','Zoho.services','Zoho.directive'])
.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('login');
$stateProvider
.state('login',{
url: '/login',
templateUrl : 'pages/login.html',
controller : 'loginController'
})
.state('signUp',{
url: '/signup',
templateUrl : 'pages/login.html',
controller : 'signUpController'
});
Here only the login part is executing but signup is not working, Im using both signup and login code in a single page with ng-show and ng-hide methods
login.html
<div class="container-fluid login" ng-show="showDiv">
<div class="col-lg-4 col-sm-12 col-md-4">
<h1 class="title">Login</h1>
<input placeholder="Username" type="text" ng-model="loginData.username" required="required"/>
<input placeholder="Mobile" type="number" ng-model="loginData.mobile" required="required"/>
<button class="btn-signUp" ng-click="login(loginData)">Login <span class="glyphicon glyphicon-log-in"></span></button>
<p>New User <button class="btn-link" ng-click="showDiv=false">SignUp</button></p>
</div>
</div>
<div class="container-fluid login" ng-hide="showDiv">
<div class="col-lg-4 col-sm-12 col-md-4">
<h1 class="title">Register</h1>
<input placeholder="Name" type="text" ng-model="signUpData.name" required="required"/>
<input placeholder="Username" type="text" ng-model="signUpData.username" required="required"/>
<input placeholder="Mobile" type="number" ng-model="signUpData.mobile" required="required"/>
<input placeholder="Email" type="email" ng-model="signUpData.email" required="required"/>
<button class="btn-signUp" ng-click="signUp(signUpData)">SignUp <span class="glyphicon glyphicon-log-in"></span></button>
<p>Already User<button class="btn-link" ng-click="showDiv=true">Login</button>
</div>
</div>

angularfire routing the pages on two or three clicks of a button

I have a controller for signing in firebase
$scope.addUser = function() {
firebase.auth().signInWithEmailAndPassword($scope.Email,$scope.Password).then(function(authData) {
authenticated = true;
console.log("Logged in as:", authData.uid, authenticated);
$location.path("/user_manual");
}).catch(function(error) {
authenticated = false;
console.error("Authentication failed:", error);
$location.path("/");
});
};
And a login.html form
<center><h1>Login</h1></center>
<form class="form-horizontal" role="form">
<div class="form-group">
<div class="col-sm-2"></div>
<label class="col-sm-2 control-label">Email:</label>
<div class="col-sm-4">
<input class="form-control" id="Email"
ng-model="Email" placeholder="Email"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-2"></div>
<label class="col-sm-2 control-label">Password:</label>
<div class="col-sm-4">
<input type="password" class="form-control" id="Password"
ng-model="Password" placeholder="Password"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-2"></div>
<label class="col-sm-2 control-label"></label>
<div class="col-sm-4">
<a ng-click="addUser()" class="btn btn-small btn-primary">Login</a>
</div>
</div>
</form>
</div>
As I click on login button it doesn't load user_manual.html for the first time but clicking it on three times it loads user_manual.
The same is with logout button:
I have logout function :
scope.logout = function(){
$window.alert("Do you really want to logout?");
firebase.auth().signOut().then(function() {
$location.path("/");
}).catch(function(error) {
});
And a logout button as:
<a ng-click="logout()" ng-confirm-click="Do you want to logout" class="btn btn-small btn-primary">logout</a>
It also redirects to $location.path("/") on clicking the button twice.
Here is the main controller app.js:
var app = angular.module('myApp',['ngRoute','firebase','ng-fusioncharts','chart.js','720kb.datepicker']);
var config = {
*******************************
};
firebase.initializeApp(config);
var user = firebase.auth().currentUser;
app.config(function($routeProvider){
$routeProvider
.when('/', {
controller: 'UserAdd',
templateUrl: 'views/users/user_login.html'
})
.when('/user_manual', {
controller: 'UserManual',
templateUrl: 'views/user_manual/user_manual.html'
})
.otherwise({
redirectTo: '/'
});
});
Why the buttons not work on a single click action?

how to close modal after submit in angularjs

i know have many result in this question but no one give work answer for me.
html 1:
<button class="basebtn logbtn" ng-click="openlog()">LOGIN</button>
<button class="basebtn regbtn" ng-click="openreg()">SIGN UP</button>
html 2:
<div ng-controller="main">
<center><img class="img-login" ng-src="../images/form-logo.png"/></center>
<form class="login" name="log" ng-submit="login()" novalidate>
<div class="form-group login-form" ng-class="{'has-error' : isInvalid(log.email) ,'has-success' : isValid(log.email)}">
<input type="email" class="form-control" name="email" ng-model="user.email" required placeholder="Email">
<div class="alert alert-danger" role="alert" ng-show="isInvalid(log.email)">Enter valid email</div>
</div>
<div class="form-group login-form" ng-class="{'has-error' : isInvalid(log.password) ,'has-success' : isValid(log.password)}">
<input type="password" class="form-control" name="password" ng-model="user.password" required placeholder="Password">
<div class="alert alert-danger" role="alert" ng-show="isInvalid(log.password)">This Feild is required</div>
</div>
<div class="form-group" style="text-align:center;">
<input type="submit" class="logbnt" value="LOGIN" ng-disabled="! log.$valid" data-dismiss='modal'/>
</div>
</form>
angular :
$scope.login = function(){
$http.post("www.example.com/login",$scope.user).then(function(res){
localStorage.setItem("token",res.data.token);
//how i close the modal ???
});
}
//here create the modal
$scope.openlog = function () {
$scope.$modalInstance = $uibModal.open({
templateUrl:"login.html",
});
}
that my code , how i close in $http result the modal ?
You can do this,
$scope.login = function(){
$http.post("www.example.com/login",$scope.user).then(function(res){
localStorage.setItem("token",res.data.token);
$modalInstance.dismiss('cancel');
});
};

Connect Express nodemailer with Angular

I'm trying to make a contact form, and the server side is working pretty well. But I don't know how to connect Angular to the html form and send it with Express. Any would appreciate any help.
My Express
router.get('/sendQuote', function(req, res) {
var data = req.query;
var mailOptions = {
from: 'planacte#gmail.com', // sender address
name: data.contactName,
email: data.contactEmail,
to: data.email, // list of receivers
subject: "Request for a Quote from " + data.contactName, // Subject line
text: data.contactMsg, // plaintext body
html: '<p> email: ' + data.contactEmail +
'</p><p> phone: ' + data.contactPhone + '</p><br>'
+data.contactMsg // html body
};
console.log(mailOptions)
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
});
So, my html:
<form id="contact" class="contact-form" ng-submit="sendMail()" novalidate>
<div class="message"></div>
<div class="col-md-5 col-sm-5 col-xs-12 animated hiding" data-animation="slideInLeft">
<div class="form-group">
<input type="text" name="name" class="nameform form-control input-lg" placeholder="name" ng-model="contactName" required>
</div>
<div class="form-group">
<input type="email" name="email" class="emailform form-control input-lg" placeholder="email" ng-model="message.contactEmail" required>
</div>
<div class="form-group">
<input type="text" name="phone" class="phoneform form-control input-lg" placeholder="phone" ng-model="message.contactPhone">
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<div class="form-group">
<textarea name="message" class="messageform form-control input-lg" placeholder="custom text" ng-model="message.contactMsg" required></textarea>
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<input type="submit" class="btn btn-custom up form-button" value="Send Message">
And the main problem is here, how to glue Angular with HTML and Express. I can send emails, but get undefined in the fields of Name, Email and so on. :
app.controller('MainCtrl', ['$scope', '$interval', '$http', '$location', '$anchorScroll',
function($scope, $interval, $http, $location, $anchorScroll) {
$scope.sendMail = function () {
$scope.message = {};
$http.get('/send/sendQuote', $scope.message).
success(function(data, status, headers, config) {
// $scope.message = data.message;
console.log($scope.message)
});
}
}]);
I think you should start by making this request a POST and not a GET request.
router.post('/sendQuote', function(req, res) {
var data = req.body;
var mailOptions = {
from: 'planacte#gmail.com', // sender address
name: data.contactName,
email: data.contactEmail,
to: data.email, // list of receivers
subject: "Request for a Quote from " + data.contactName, // Subject line
text: data.contactMsg, // plaintext body
html: '<p> email: ' + data.contactEmail +
'</p><p> phone: ' + data.contactPhone + '</p><br>'
+data.contactMsg // html body
};
console.log(mailOptions)
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
res.send(200); // let the client know it sent ok.
});
Now, let's take a look at your Angular code. It seems you want the object $scope.message to hold your form fields data. You should define this as an object at the beginning of your controller.
app.controller('MainCtrl', ['$scope', '$interval', '$http', '$location', '$anchorScroll',
function($scope, $interval, $http, $location, $anchorScroll) {
$scope.message = {};
$scope.sendMail = function () {
//$scope.message = {}; -- this was clearing the object
$http.post('/send/sendQuote', $scope.message).
success(function(data, status, headers, config) {
// you can clear $scope.message if you want here
// $scope.message = data.message;
console.log($scope.message)
});
}
}]);
HTML had one ng-model not binding to the message object:
<form id="contact" class="contact-form" ng-submit="sendMail()" novalidate>
<div class="message"></div>
<div class="col-md-5 col-sm-5 col-xs-12 animated hiding" data-animation="slideInLeft">
<div class="form-group">
<input type="text" name="name" class="nameform form-control input-lg" placeholder="name" ng-model="message.contactName" required>
</div>
<div class="form-group">
<input type="email" name="email" class="emailform form-control input-lg" placeholder="email" ng-model="message.contactEmail" required>
</div>
<div class="form-group">
<input type="text" name="phone" class="phoneform form-control input-lg" placeholder="phone" ng-model="message.contactPhone">
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<div class="form-group">
<textarea name="message" class="messageform form-control input-lg" placeholder="custom text" ng-model="message.contactMsg" required></textarea>
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<input type="submit" class="btn btn-custom up form-button" value="Send Message">

AngularJS Form controller from directive

I am trying to submit a simple contact form. The form is inside a bootstrap modal (don't think that makes any difference) but the controller is in a directive.
The html for the form is as followed:
<form name="contactForm" ng-submit="contactForm()" novalidate>
<div class="form-group">
<div class="col-lg-6 col-md-6 col-sm-6">
<input type="text" placeholder="Full name" name="name" ng-minlength="3" max="20"
ng-model="name" id="name" class="form-control">
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<input type="email" ng-minlength="4" placeholder="Email address" name="contactEmail"
ng-model="email" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-lg-12 col-md-12 col-sm-12">
<input type="text" ng-model="subject" name="subject" ng-minlength="10" id=""
placeholder="Subject" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-lg-12 col-md-12 col-sm-12">
<textarea class="form-control" ng-model="message" name="message" ng-minlength="10"
placeholder="Your message"></textarea>
</div>
</div>
<div class="modal-footer">
<div class="col-lg-12 col-md-12 col-sm-12">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
</div>
</form>
Which i think is all good. The body of my controller looks like this
$rootScope.contactForm = contactForm();
function contactForm() {
console.log('triggered!');
var contactFormVars = {
name: $rootScope.name,
contactEmail: $rootScope.contactEmail,
subject: $rootScope.subject,
message: $rootScope.message
}
// With Promise
Stamplay.Object('contactform')
.save(contactFormVars)
.then(function(res) {
console.log('yes!');
}, function(err) {
console.log('No!');
})
}
return directive;
};
EDIT: Controller now looks like this:
function contactForm($rootScope,$stamplay,$q) {
$rootScope.data = {}
$rootScope.data = {
name: $rootScope.data.name,
contactemail: $rootScope.data.contactemail,
subject: $rootScope.data.subject,
message: $rootScope.data.message
}
Stamplay.Object("contactform")
.save($rootScope.data, function (err, res) {
console.log(res);
console.log(err);
// res is the new car object
});
}
When i click the submit button I get the following error which i've been Googling
Error: v2.contactForm is not a function. (In 'v2.contactForm()', 'v2.contactForm' is an instance of FormController)
fn
Any help with this is appreciated.
EDIT
Ok so now i've moved the js from a directive and placed it in to the main controller. At the moment its not making any difference, only that the error has changed very slightly:
angular.js:12722Error: v4.contactForm is not a function. (In 'v4.contactForm(ensureSafeObject(v5,text))', 'v4.contactForm' is an instance of FormController)
fn
Not sure what the difference between v2 and v4 is.
Any advice to get past this blocker is appreciated.

Resources