rendering data to html file using express render method - javascript

i want to render data concerning the authentication status to my login form which is at index.html:
i tried to do that
response.render(__dirname + "/CERIGame/index.html", {
errors: "authentication failed"
});
but it doesn't work; need help
here is my project tree:
and here my server.js file:
app.get('/login', function(request, response) {
var username = request.query['username'];
var password = request.query['password'];
if (username == "" || password == "") {
response.render(__dirname + "/CERIGame/index.html", { errors: "authentication failed" });
}
});
i want to display the errors variable content in my index.html
<div class="body"></div>
<div class="grad"></div>
<div class="col-xs-4">
<div class="header">
<div><b>Bienvenue sur<span>qUIZZ CERI</span><b></div>
</div>
</div>
<br>
<form class="col-xs-8" method="get" action="/login">
<div class="login">
<input type="text" placeholder="username"name="username"><br>
<input type="password" placeholder="password"name="password"><br>
<input type="submit" value="Login">
</div>
</form>

Related

Form with recaptcha redirect after submission

I'm trying to learn express/nodejs and implement a form, where after recaptcha you can click and download a file. But after form submission I'm being redirected to localhost/submit with only status code on the page. This is driving me crazy, I just want to enable download button after passing recaptcha. I believe this is obvious, but not for me.
server.js file
// Load Node modules
var express = require("express");
const fetch = require("isomorphic-fetch");
// Initialise Express
var app = express();
// Render static files
app.use(express.static("public"));
// Port website will run on
app.listen(8080);
// To accept HTML form data
app.use(express.urlencoded({ extended: false }));
// Here, HTML form is submit
app.post("/submit", (req, res) => {
const name = req.body.name;
// getting site key from client side
const response_key = req.body["g-recaptcha-response"];
// Put secret key here, which we get from google console
const secret_key = "6LdGoQohAAAAAJe6wa_-xayew_ht3N6Lm-kSdbW9";
console.log(res);
// Hitting POST request to the URL, Google will
// respond with success or error scenario.
const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${response_key}`;
// Making POST request to verify captcha
fetch(url, {
method: "post",
})
.then((response) => response.json())
.then((google_response) => {
// google_response is the object return by
// google as a response
if (google_response.success == true) {
// if captcha is verified
return res.sendStatus(200);
} else {
// if captcha is not verified
console.log(google_response);
return res.sendStatus(400);
}
})
.catch((error) => {
// Some error while verify captcha
return res.json({ error });
});
});
html form
<form class="main-form" action="/submit" method="post" id="myForm">
<div class="form-row">
<div class="form-element">
<label for="form-delivery">Номер поставки:</label>
<input type="text" name="delivery" required id="form-delivery" />
</div>
<div class="form-element">
<label for="form-num">Номер ТТН:</label>
<input type="text" name="delivery2" id="form-num" />
</div>
</div>
<div class="form-row">
<div class="form-element">
<label for="form-date" req>Дата формирования:</label>
<input type="date" name="delivery3" id="form-date" required />
</div>
<div class="form-element">
<label for="form-client">Клиент:</label>
<input type="text" name="delivery4" id="form-client" />
</div>
</div>
<div class="form-row">
<div class="form-element">
<label for="form-car">Гос. номер:</label>
<input type="text" name="delivery5" id="form-car" />
</div>
<div class="form-element">
<label for="form-cert">Номер сертификата:</label>
<input type="text" name="delivery6" id="form-cert" />
</div>
</div>
<div id="g"></div>
<button class="download-link" type="submit">Скачать</button>
</form>

Server unable to find view for POSTbut can find it in GET

I have some code that is supposed to validate a user logging into my server, however it doesn't want to post it. My get request has no problem loading the very same "/login" as my post but for some reason it doesn't want to load it during the POST. Sorry if my code is a little inefficient and hard to read, still trying to get the hang of javascript.
app.post("/login", (req, res) => {
req.body.userAgent = req.get('User-Agent');
dataServiceAuth.checkUser(req.body).then((user) => {
req.session.user = {
userName: user.username,
email: user.email,
loginHistory: user.loginHistory
}
res.redirect('/employees');
}).catch((err) => {
res.render("login", {errorMessage: err, userName: req.body.userName});
});
});
and the function in the POST
module.exports.checkUser = function (userData) {
return new Promise(function (resolve, reject) {
User.find({ user: userData.userName }).exec().then((user) => {
if (user == undefined || user.length == 0) {
reject("Unable to find user: " + userData.userName);
}
else if (user[0].password != userData.password) {
reject("Incorrect Password for user: " + userData.userName);
}
else if (user[0].password == userData.password) {
users[0].loginHistory.push({dateTime: (new Date()).toString(), userAgent: userData.userAgent});
user[0].update({userName: userData.userName}, {$set: {loginHistory: user[0].loginHistory}}.exec().then((user) => {
resolve(user[0]);
}).catch((err) => {
reject("There was an error verifying the user: ${err}");
}))
}
}).catch((err) => {
reject("Unable to find user: " + userData.user);
});
});
};
My Tree looks like this
and my Handlebars file looks like this
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Log In</h2>
<hr />
{{#if errorMessage}}
<div class="alert alertdanger">
<strong>Error:</strong> {{errorMessage}}</div>
{{/if}}
<form method="post" action="/login">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input class="form-control" id="userName" name="userName" type="text" placeholder="User Name" required value=""
/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input class="form-control" id="password" name="password" type="password" placeholder="Password" required />
</div>
</div>
</div>
<input type="submit" class="btn btn-success pull-right" value="Login" />
</form>
</div>
</div>
</div>
</body>
</html>
Express version 4 and above requires extra middle-ware layer to handle POST request. This middle-ware is called as ‘bodyParser’. This used to be internal part of Express framework but here I think you need to install it separately like this npm install --save body-parser
Firstly, You should realize that requesting the same route through GET and POST methods does different things.
When you use the GET method, the reason that it has no problem loading the page is because (from what I assume) you would have specified a specific file (probably this login form) to be rendered when a request is received.
In case of the POST request though, you are carrying out operations on the form data sent with the request, and hence there could be a number of reasons you're facing issues with it. Maybe you haven't configured bodyParser to parse nested objects, as Yaswant's answer stated. Or maybe there's some other issue in your code.
It would be helpful if you could give a little more detail on what error you're facing, and if you could post your complete app.js file.

AngularJS User Login to Json file

I am currently trying to create a user login page where the user information is stored on a json file. I have created my GET method to the file but I cannot seem to redirect after the user has logged in successfully. Can you help me out?
I know that user login and validation done on the client side is A BAD IDEA but that is how I want to do it, without using a database.
Here is my HTML code:
<body ng-controller="myCtrl">
<form id="login-form">
<h3>User Login</h3>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<button type="submit" class="btn btn-default" id="login-button" ng-click="LogOn()">Login</button>
</form>
</body>
My JavaScript code:
var app = angular.module('myApp', [ ]);
app.controller("myCtrl",['$scope', '$http', function($scope, $http){
$scope.LogOn = function(){
$http.get('data.json').then(function(data){
$scope.users = data;
});
if (data.email == email) && (data.password = password{
window.location.href = 'www.google.com';
}
};
}]);
My JSON File:
[
{
"email":"something#yahoo.com",
"Password":"password"
},
{
"email":"test#yahoo.com",
"password":"test999"
},
{
"email":"xxx#mail.xx",
"password":"xxx"
}
]
Please try to open the link and check and run the code which is deployed in w3 schools
https://www.w3schools.com/code/tryit.asp?filename=FDVZY3NXVYG6
Put redirection code inside then
$http.get('data.json').then(function(data){
$scope.users = data;
if (data.email == email && data.password == password) {
window.location.href = 'www.google.com';
}
});
Obviously the if bellow has to be inside the .then( callback
if (data.email == email && data.password == password) {
window.location.href = 'www.google.com';
}

Internet Explorer 9 doesn't send data to the database in Nodejs

I have an express website that has a form in it. That form allows us to send users information data to the database (mysql). It came to my attention that the submit functionality doesn't send any data to the database when we use Internet Explorer. The other browsers work perfectly fine. But IE sends nothing to the database. When the submit has been clicked with IE, the form sends us to the confirmation page indication submission is successful. But nothing inside the database. The code that I use is below. This is the admission.js router file.
router.post('/add-application', function (req, res) {
var first_name = req.body.first_name;
var middle_name= req.body.middle_name;
var last_name = req.body.last_name;
//check errors
req.checkBody('first_name', 'First name is required').notEmpty();
var errors = req.validationErrors();
if (errors) {
res.render('/error', {
errors:errors,
first_name : first_name,
middle_name : middle_name,
last_name : last_name
});
} else {
var applications = {
first_name : first_name,
middle_name : middle_name,
last_name : last_name
};
}
var query = connection.query('INSERT INTO applications SET ?', applications, function (err, result) {
console.log('Error:' + err);
console.log('Success: ' + result);
});
req.flash('success_msg', 'Application Inserted!');
res.redirect('/');
});
And I have the following scripts for IE on the header as well:
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
And here is the form:
<div class="container">
<div class="row">
<h2>Register</h2>
<form class="form-register" method="post" action="/admission/add-application">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
<h4><i class="fa fa-fw fa-check"></i>Information</h4>
</div>
<div class="panel-body">
<label>First Name</label>
<input name="first_name" type="text" class="form-control" placeholder="Enter the first name" required><br />
<label>Middle Name</label>
<input name="middle_name" type="text" class="form-control" placeholder="Enter the middle name" ><br />
<label>Last Name</label>
<input name="last_name" type="text" class="form-control" placeholder="Enter the last name" required ><br />
</div>
</div>
</div>
<div class="col-lg-12">
<input style="width:25%" class="btn btn-lg btn-primary btn-block" type="submit" name="submit" value="Submit" />
</div>
</form>
</div>
</div>
Internet Explorer 9 || < doesn't support major components. Websockets and submitting form functionalities are just two of them. So the solution is very simple. DO NOT use IE.

Angular validations: Restrict server request if user enters invalid email or password

<form name="LPform" novalidate>
<div class="form-row clearfix">
<label class="lbl-fld" style="margin-left: 12%;width:20%;">Email ID</label>
<input class="mob-adj-inpbx " type="email" name="uemail" ng-model="useremail" placeholder=" me#example.com" ng-required="true"/>
<div class="valid-chk validation-loginpopup" ng-show="LPform.uemail.$dirty && allow_Invalid">
<i style="font-size: 1.15em;padding:0px;" ng-class="{'false':'icon-close', 'true': 'icon-correct'}[LPform.uemail.$valid]" class="icon-correct"></i>
</div>
<div class="error-prompt" ng-show="LPform.uemail.$dirty && allow_Invalid">
</div>
</div>
<div class="form-row clearfix">
<label class="lbl-fld" style="margin-left: 12%;width:20%;">PASSWORD</label>
<input class="mob-adj-inpbx" type="password" name="upassword" ng-model="userpassword" placeholder=" password" ng-required="true"/>
<div class="valid-chk validation-loginpopup" ng-show="LPform.upassword.$dirty && allow_Invalid">
<i style="font-size: 1.15em;padding:0px;" ng-class="{'false':'icon-close', 'true': 'icon-correct'}[LPform.upassword.$valid]" class="icon-correct"></i>
</div>
<div class="error-prompt" ng-show="LPform.upassword.$dirty && allow_Invalid">
</div>
</div>
<div id="server_message" class="form-row clearfix basic-error-msg-loginpopup" ng-show="server_message">
{{server_message}}
</div>
<div class="btn-container clearfix mobile-adj" style="margin-left:17.2%;">
<div class="btn-wrap btn-loginpopup">
<input style="max-height:40px;width:121%;" type="submit" name="commit" value="LOGIN" ng-click="login_request()"/>
</div>
</div>
</form>
This part is displayed to the user and the inputs are validated using angular validations. All validations are working fine.
$scope.login_request = function(){
if(LPform.useremail.$valid && LPform.userpassword.$valid) {
$scope.allow_Invalid = "true";
$http({
method: 'POST',
url: '/users/home_login',
data: {email: $scope.useremail, password: $scope.userpassword}
}).success(function (response) {
console.log(response);
window.location = response.location;
}).error(function (response) {
console.log(response);
$scope.server_message = response.server_message;
});
}
else if(!LPform.useremail.$valid) {
$scope.allow_Invalid = "true";
$scope.server_message = "Please enter valid email.";
}
else if(!LPform.userpassword.$valid) {
$scope.allow_Invalid = "true";
$scope.server_message = "Please enter valid password.";
}
else{
$scope.allow_Invalid = "true";
$scope.server_message = "Request Failed.";
}
};
This part is in javascript file where I want to use the validations to decide whether to send a request to the server or not. The conditions I have used in the if else clause is not working, which I randomly tried btw. I am aware that I can disable Login button, however, I don't want to implement this that way.
I believe your problem is that the form name is bound to $scope and isn't a global variable.
In controller change
LPform
To
$scope.LPform

Categories