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.
Related
Any help appreciated. I've got an app that pulls data from google books api. From each book page, the user is able to leave a review. The path to the review is /review/${isbn Number}. Each page has a path based on the isbn. The review routes work and I'm able to make the post request through insomnia/postman with no issues, I'm just having trouble with the front-end js in pulling the data from the input boxes to make the post request. I'm not sure if the issue is because the isbn being in the path. Below is my front-end javascript that I am unable to fix.
const newFormHandler = async (event) => {
event.preventDefault();
console.log("testing")
const description = document.querySelector('#description').value;
const reviewTitle = document.querySelector('#reviewTitle').value;
const isbn = window.location.search
if (description) {
const response = await fetch(`api/review/${isbn}`, {
method: 'POST',
body: JSON.stringify({ description, reviewTitle }),
headers: {
'Content-Type': 'application/json',
},
});
if (response.ok) {
document.location.reload();
} else {
alert('Failed to create review');
}
}
};
document
.querySelector('.form-group')
.addEventListener('submit', newFormHandler);
My form is below:
<div class="col form-group">
<div class ="card reviewCard" style = "background-color:#fcf8f3; color: #65625e;">
<form id="blog-form">
<div>
<label for="reviewTitle">Review Title</label>
<input
value="{{title}}"
id="reviewTitle"
name="reviewtitle"
placeholder="Enter Review Title"
type="text"
required="required"
class="form-control"
data-bv-notempty="true"
data-bv-notempty-message="The title cannot be empty"
/>
</div>
<div>
<label for="review">Review</label>
<textarea
id="description"
name="review"
cols="40"
rows="10"
required="required"
class="form-control"
>{{description}}</textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
And here is my route that works fine with insomnia, no issues.
router.get('/review/:id', async (req, res) => {
try {
const isbn13 = req.params['id'];
const reviewData = await Review.findAll({ where: {
isbn:isbn13
},
include: [
{
model: User,
attributes: ['name'],
}
]
})
const reviews = reviewData.map((review) => review.get({ plain:true}));
// console.log(isbn13);
res.render('review', {
isbn: isbn13, reviews:reviews
});
} catch (err) {
console.log(err)
}
});
Any help appreciated. I tried to pull in the isbn number from the path, but with no success. I think I have it formatted wrong somehow.
First console log your req
You should see the body containing some data.
In a get request the they are arguments in the URL.
In a Psot request they are in the body of the request.
I am new to working with databases. I've been trying to create a login/register webpage using only HTML, Js and MongoDB in my codes in order to practice. I have successfully made a function for login, yet I've been struggling to create a function for registering using the Fetch API.
I am aware that my register code is used rather for a login function, but I used it as a template for the sign up one.
I'd appreciate it if anyone can help me fix the register function using Fetch() in order to not give me 401 and to be able to add the new user's email and password to my database. Thank you.
const btnAccount = document.querySelector('.account .submit')
btnAccount.addEventListener('click', event => {
event.preventDefault()
const email = emailAccount.value
const pass = passAccount.value
const pass2 = pass2Account.value
if (email && pass && pass2) {
if (pass === pass2) {
// The data i wish to add to my mongoDB users database:
const account = {
strategy: "local",
email : emailAccount.value,
password: passAccount.value
}
fetch('http://localhost:3030/authentication', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(account)
}).then(response => {
return response.json()
}).then(result => {
console.log(result)
document.forms[1].reset();
})
.catch(err => {
// If I got some errors regardings the DB or in the code itself:
console.log('eroare:', err)
alert(`Something's wrong. I can feel it!`)
})
}
else {
// Passwords not the same:
alert('Parolele nu coincid!')
}
}
else {
// Not all fields written:
alert('Completeaza bah campurile...')
}
})
<main>
<form class="account">
<div>
<label for="email">Email:</label>
<input required type="email">
</div>
<div>
<label for="password">Password:</label>
<input required type="password" class="password">
</div>
<div>
<label for="password2">Verify Password:</label>
<input type="password" class="password2">
</div>
<div>
<button class="submit">Create new account</button>
</div>
<div>
I already have an account
</div>
</form>
<button class="fetchItems">Load ITEMS</button>
<div class="output"></div>
</main>
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");
});
} ;
})
I'm trying to save an array into a JSON file that's located on a webserver.
The response is successful but when I open the JSON it's completely empty.
I've tried to create a JSON object of my own manually but it yielded same results.
Here's the process:
app.controller('BookController', ['$window', '$http', function ($window, $http) {
this.contacts = [];
this.exportContacts = function(contacts){
$http({
method: "POST",
url: '/data/contacts.json',
headers: { 'Content-Type': 'application/json' },
data: contacts
}).then(function goodCall(){
$window.alert("Save done!");
}, function badCall(){
$window.alert("Failed to save error! error: " + $http.status);
});
};
}]);
I fill the array with inputs via form:
<form name="addCont" ng-show="showForm" ng-controller="ContactController as contactCtrl" ng-submit="contactCtrl.addContact(addCont, bookCtrl.contacts)" novalidate>
<label>
First Name:
<input name="fname" type="text" required ng-pattern="/^(\D)+$/" ng-model="contactCtrl.contact.firstName"></input>
<span style="color:red" ng-show="addCont.fname.$dirty && addCont.fname.$invalid">
<span ng-show="addCont.fname.$error.required">First Name is required.</span>
<span ng-show="addCont.fname.$error.pattern">First name must contain letters only!</span>
</span>
</label>
<label>
Last Name:
<input name="lname" type="text" ng-pattern="/^(\D)+$/" ng-model="contactCtrl.contact.lastName"></input>
<span style="color:red" ng-show="addCont.lname.$dirty && addCont.lname.$invalid">
<span ng-show="addCont.lname.$error.pattern">Last name must contain letters only!</span>
</span>
</label>
<label>
Phone Number:
<input name="phone" type="tel" required ng-model="contactCtrl.contact.phone" ng-minlength="9" ng-maxlength="10" ng-pattern="/^(\d)+$/"></input>
<span style="color:red" ng-show="addCont.phone.$dirty && addCont.phone.$invalid">
<span ng-show="addCont.phone.$error.minlength">Phone number is too short!</span>
<span ng-show="addCont.phone.$error.maxlength">Phone number is too long!</span>
<span ng-show="addCont.phone.$error.required">Phone number is required!</span>
<span ng-show="addCont.phone.$error.pattern">Must not contain letters!</span>
</span>
</label>
<label>
Notes:
<input name="notes" type="text" ng-model="contactCtrl.contact.notes"></input>
</label>
<input type="submit" value="Submit" ng-disabled="addCont.fname.$invalid || addCont.lname.$invalid || addCont.phone.$invalid" />
</form>
So the array should look somethings like this:
[{
firstName: "Tim",
lastName: "asdxc",
notes: "asdasd",
phone: "0532753940"
},{
firstName: "Timz",
lastName: "asdasd",
notes: "asdasd",
phone: "123123123"
}]
Do I somehow need to parse the array before sending it?
As far as I understand your code, you are missing an important peace. You need some RESTful like service on your server. Otherwise your not able to save/write to files on your server.
I recommend you to get familiar with node and may be express for the start.
The url you give to $http should be a web service.
It will not work with a file.
You have to create a webservice who create the file on server side ( php / node.js / java ... ) and call it from $http
I think url property must be 'api/contacts':
Given that you must have a web service or web api controller: ContactsController
$http({
method: "POST",
url: 'api/contacts',
headers: { 'Content-Type': 'application/json' },
data: contacts
}).then(function goodCall(){
$window.alert("Save done!");
}, function badCall(){
$window.alert("Failed to save error! error: " + $http.status);
});
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';
});