I am creating a Restful API on Node.js and storing data into Mongodb. and working on user registration API.
app.js
apiRoutes.post('/signup', function(req, res) {
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,
password:req.body.password
});
console.log(req.body.name);
// save the user
newUser.save(function(err, data) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}else{
console.log(data);
res.json({success: true, msg: 'Successful created new user.'});}
});
}
});
Consuming API using Angular.js
//factory for user register
app.factory('RegistrationFactory', function($resource){
return $resource('/api/signup/:id',{id:'#_id'},{update:{method:'PUT'}});
});
//controller for registration
app.controller('registerCtrl', function($scope, RegistrationFactory, $location){
$scope.regUser=new RegistrationFactory();
$scope.register=function(){
console.log($scope.newUser);
$scope.regUser.$save(function(){
console.log("User Registerd");
});
} ;
})
register.html
<div class="post" ng-controller="registerCtrl">
<form method="post">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ng-model="newUser.name" />
</div>
<div class="form-group">
<label>Password</label>
<input type="text" class="form-control" name="password" ng-model="newUser.password"/>
</div>
<div class="form-group">
<button class="btn btn-success" ng-click="register()">Register</button>
</div>
</form>
</div>
So, My problem is that, this API is working fine on POSTMAN but its not working on my HTML form. Please review my code. Whenever I click on Register button its seems like that on button click API is not hitting. nothing is happening.
Please review my code and suggest me solution.
Thanks.
from angular controller you are not passing the newUser object to $resource or regUser change the controller code to below
//controller for registration
app.controller('registerCtrl', function($scope, RegistrationFactory, $location){
$scope.register=function(){
console.log($scope.newUser);
$scope.regUser=new RegistrationFactory($scope.newUser);
$scope.regUser.$save(function(){
console.log("User Registerd");
});
} ;
})
Related
I am new using Angularjs and I am having an issue parsing a JSON response. I am doing client side authentication , I know it's bad practice, but I want it to learn.
HTML Code :
<form ng-submit="loginform(logcred)" class="ng-scope ng-pristine ng-valid center" name="logform"><br/><br>
<tr ng-repeat="logcred in serverinfo"></tr>
<div>
<label form="emailinput"><b>Email</b></label>
<input type="email" class="form-control" name="uname" id="emailinput" placeholder="you#example.com" ng-model="logcred.username" >
</div>
<div>
<label form="pwdinput"><b>Password</b></label>
<input type="password" class="form-control" name="pwd" id="pwdinput" placeholder="*******" ng-model="logcred.password">
</div>
<div>
<button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
<button class="btn btn-primary" ng-click="submit()">Login</button>
</div>
<br/>
</form>
AngularJS :
var myApp = angular.module('myApp', []);
myApp.controller('credientials', function($scope, $http) {
/* server side response*/
$http.get('http://localhost:3000/loginfo')
.then(
function successCallback(response){
$scope.serverinfo = response.data;
});
/* client-side response*/
$scope.loginform = function(userData){
$http({
url: 'http://localhost:3000/loginfo',
method: 'POST',
data: userData
})
.then(
function successCallback(response){
if (userData.username === response.data.username && userData.password === response.data.password) {
$scope.signinfo = response.data;
}else{
console.log("Error: " + response)
}
});
}
});
Response data:
Object { username: "admin#evol.io", password: "admin" }
In the Above code I am execute a POST request on the server, specifying username and password inserted by the user. The server should check the if condition from server, to check if there are any rows with that name and password. If yes return true, if false return false. then the client should parse this response. I already fetch the response from server , but I don't know why the if condition is failing to give the response.
What am I doing wrong?
Any help / advice would be greatly appreciated.
I am attempting to send form data from a page to MongoDB in Node.js.
The issue I am running into is when I am clicking the 'Add Group' button to submit the data.. the page tries to complete the request but seems to get stuck when trying to push the data to the database. So it then is just sitting there, stuck, trying to take the inputted data and place it into the database.
Here is my Group Model:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
path = require('path');
var GroupsSchema = new Schema({
groupName: {type: String}
});
GroupsSchema.virtual('uniqueId')
.get(function(){
return this.filename.replace(path.extname(this.filename), '');
});
module.exports = mongoose.model('Groups', GroupsSchema);
Here is my Group Controller:
var Models = require('../models');
module.exports = {
index: function(req, res){
var viewModel = {
groups: []
};
Models.Group.find({}, function(err, groups){
if(err){
throw err;
}else{
viewModel.groups = groups;
res.render('addGroup', {title: 'Admin Add Product Group', adminloggedin: true, subtitle: 'Add a Group', underheaderp: ''});
}
});
},
create: function(req, res){
var saveGroup = function(){
Models.Group.find({}, function(err, groups){
if(groups.length > 0){
saveGroup();
}else{
Models.Group.find({},function(err, groups){
if(err){
throw err;
}else{
var newGrp = new Models.Group({
groupName: req.body.groupname
});
newGrp.save(function(err, group){
console.log('Successfully inserted Group');
res.redirect('admin/addGroup');
});
}
});
}
});
};
saveGroup();
}
};
My current Routes:
var express = require('express'),
router = express.Router(),
addGroup = require('../controllers/addGroup');
module.exports = function(app){
router.get('/admin/addGroup', addGroup.index);
router.post('/admin/addGroup', addGroup.create);
app.use(router);
}
And my addGroup handlebars page
<!-- Add a Product Group Form -->
<div class="row">
<div class="col-md-6">
<form action="/admin/addGroup" method="post">
<fieldset class="form-group">
<label for="newGroupName">Group Name:</label>
<input type="text" class="form-control" name="groupname">
</fieldset>
<fieldset class="form-group">
<label for="groupImageFolder">Image Folder Name:</label>
<input type="text" class="form-control" name ="groupImageFolder">
</fieldset>
<button type="submit" class="btn btn-success" type="button">Add Group</button>
</form>
</div>
</div>
Unfortunately, I have yet to find a great way to debug my applications as I am still a new programmer. Any recommendations would be great as well.
The problem must be in my controller :create
Possibly where I am defining my var newGrp and trying to set it to my group models?
How can I fix this to make it so it saves the inputted data to MongoDB?
Any help is greatly appreciated.
At the moment I have javascript that allows all users from the (_User) table to log in. I have set up a Role called (Admins) within the role table and assigned one user to this role. Would this be an if statement?
At the moment this is how the user logs in successfully
$scope.logIn = function(form) {
Parse.User.logIn(form.username, form.password, {
success: function(user) {
$scope.currentUser = user;
$scope.$apply();
window.location.href = "TEST.html";
},
It's easy to check whether any user belongs to a role. The only tricky part is to realize that the check includes a query, and is therefore an asynchronous operation. So first, a general purpose role checking function:
function userHasRole(user, roleName) {
var query = new Parse.Query(Parse.Role);
query.equalTo("name", roleName);
query.equalTo("users", user);
return query.find().then(function(roles) {
return roles.length > 0;
});
}
This returns a promise that will be fulfilled with a boolean, so you can call it like this:
var currentUser = Parse.User.current();
// is the user an "admin"?
userHasRole(currentUser, "admin").then(function(isAdmin) {
console.log((isAdmin)? "user is admin" : "user is not admin");
});
Apply it like this in your code. In the view:
<form role="form" name="loginForm">
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" name="email" ng-model="user.username" />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" ng-model="user.password" />
</div>
<div class="form-group">
<button class="btn btn-ar btn-primary" ng-click="pressedLogIn()">Log in</button>
</div>
</form>
And in the controller:
(function() {
'use strict';
angular.module('myApp.controllers').controller('LogInController', LogInController);
LogInController.$inject = ['$scope'];
function LogInController($scope) {
$scope.user = { username:"", password:""};
function userHasRole(user, roleName) {
// defined exactly as above
// my real app has a user service, and this would be better placed there
}
$scope.pressedLogIn = function() {
if ($scope.loginForm.$valid) {
Parse.User.logIn($scope.user.username, $scope.user.password).then(function(user) {
$scope.user = user;
return userHasRole(user, "administrator");
}).then(function(isAdmin) {
alert("user is admin = " + isAdmin);
}, function(e) {
alert(error.message);
});
}
};
}
})();
Ive built a rest-API to add todos in a mongodb. I can successfully save instances by using the following setup in postman:
http://localhost:3000/api/addtodo x-www-form-urlencoded with values text="Test", completed: "false".
Now when I try to replicate this with Angular, it doesnt work, the todo is saved but without the text and completed attributes, I cant seem to access the text or completed values from body. What am I doing wrong? Code below:
Angular-HTML:
<div id="todo-form" class="row">
<div class="col-sm-8 col-sm-offset-2 text-center">
<form>
<div class="form-group">
<!-- BIND THIS VALUE TO formData.text IN ANGULAR -->
<input type="text" class="form-control input-lg text-center" placeholder="I want to buy a puppy that will love me forever" ng-model="formData.text">
</div>
<!-- createToDo() WILL CREATE NEW TODOS -->
<button type="submit" class="btn btn-primary btn-lg" ng-click="createTodo()">Add</button>
</form>
</div>
</div>
Angular-js:
$scope.createTodo = function() {
$http.post('/api//addtodo', $scope.formData)
.success(function(data) {
$scope.formData = {}; // clear the form so our user is ready to enter another
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
REST-API:
router.post('/addtodo', function(req,res) {
var Todo = require('../models/Todo.js');
var todo = new Todo();
todo.text = req.body.text;
todo.completed = req.body.completed;
todo.save(function (err) {
if(!err) {
return console.log("created");
} else {
return console.log(err);
}
});
return res.send(todo);
});
$http.post sends it's data using application/json and not application/x-www-form-urlencoded. Source.
If you're using body-parser, make sure you've included the JSON middleware.
app.use(bodyParser.json());
Either that or change your default headers for angular.
module.run(function($http) {
$http.defaults.headers.post = 'application/x-www-form-urlencoded';
});
Back again with a new type error. Working on authentication right now. Working with AngularJS and firebase. Right now when I run my function on click of the submit button I get this in my console "TypeError: this.mRef.auth is not a function". I'm thinking it's something simple but here is my login controller:
.controller('Login', ['$scope', 'angularFire',
function($scope, angularFire) {
$scope.signin = function(){
var ref = "https://myappurl.firebaseio.com";
var auth = new FirebaseAuthClient(ref, function(error, user) {
if (user) {
// user authenticated with Firebase
console.log(user);
} else if (error) {
// an error occurred authenticating the user
console.log(error);
} else {
// user is logged out
console.log("hello");
}
});
console.log($scope);
var user = $scope.cred.user;
var pass = $scope.cred.password;
auth.login('password', {
email: user,
password: pass,
rememberMe: false
});
}
}])
Next is the html. I have it inside a controller called login and here is what is in it:
<div class="inner loginbox" ng-controler="Login"
<fieldset>
<label class ="white">Username</label>
<input type="text" id="username" ng-model="cred.user">
<span class="help-block"></span>
<label class ="white">Password</label>
<input type="password" id="password" ng-model="cred.password">
<div class="centerit rem-me">
<label class="checkbox">
<div class="white">Remember me?
<input type="checkbox" ng-model="cred.remember">
</div>
</label>
</div>
<div class="spacer1">
</div>
<a class="btn btn-inverse btn-large btn-width" id="signupsubmit" ng-click="signin()">Sign in</a>
</fieldset>
</div>
The type error I get refers to firebase-auth-client.js on line 79. In chrome I have this in the console: Uncaught TypeError: Object https://kingpinapp.firebaseio.com has no method 'auth'
When instantiating the FirebaseAuthClient, you should pass an actual Firebase reference, not just the string representation of one.
Updating your code to use the following snippet should fix your problem:
var ref = new Firebase("https://myappurl.firebaseio.com");
var auth = new FirebaseAuthClient(ref, function(error, user) {