Small issue in node js application - javascript

In my nodejs application I have route /login which uses sendFile to display my html file which takes name and password.In my server side app.js I wrote post call to take name and password.Now from my html Iam doing an ajax call to call the post call and if success I want to go to /admin page.For this I am thinking of to call in my rest call itself res.send().But Iam not aware how to send html file ..
app.get('/', function(req, res, next) {
res.sendFile(__dirname + '/public/views/home.html');
});
app.get('/login', function(req, res, next) {
res.send('respond with a resource');
res.sendFile(__dirname + '/public/views/login.html');
});
app.get('/admin', function(req, res, next) {
res.sendFile(__dirname + '/public/views/admin.html');
});
app.post('/verifylogin',function(req,res){
var username = req.headers.uname;
var password = req.headers.pwd;
var uname = "admin";
var pwd = "admin";
var login = false;
if(uname == username && pwd == password){
console.log("success");
login = true;
} else {
console.log("fail");
login = false;
}
if(login == true){
res.send();//how can I take to /admin here
} else {
res.send("Bad luck");
}
});
html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function login(){
var uname = document.getElementById('uname').value;
var pwd = document.getElementById('pwd').value;
$.ajax({
url : '/verifylogin',
type : "POST",
headers : {
"uname":uname,
"pwd" :pwd
}
});
console.log("name",uname);
}
</script>
<h1>Login</h1>
<p>
<label class="control-label">Username</label>
<input type="text" placeholder="Username" id="uname"/>
</p>
<p>
<label class="control-label">Password</label>
<input type="password" placeholder="Password" id="pwd"/><br/>
</p>
<p>
<button type="submit" class="btn btn-primary" onclick="login()">Login</button>
</p>
If login is success how can I route to /admin ..can someone help here!

As #jfriend00 stated the browser doesn't redirect from an ajax call. So you can do 1 of the 2 options i'll show.
1º Option:
Client: Remove the ajax script and handle the call through html form.
Add a form to your html page:
<form method="post" action="/verifylogin">
<label class="control-label">Username</label>
<input type="text" placeholder="Username" name="uname"/>
<label class="control-label">Password</label>
<input type="password" placeholder="Password" name="pwd"/>
<button type="submit" class="btn btn-primary">Login</button>
</form>
Server:
Use the redirect method instead of send to redirect to the specified URL.
if (login == true) {
res.redirect('/admin');
}
2º Option: Send the page as content to the ajax call and redirect the page to it.
Client:
On your ajax post add the success function:
$.ajax({
url : '/verifylogin',
type : "POST",
headers : {
"uname":uname,
"pwd" :pwd
},
success: function(data) {
window.location = data;
}
});
Server:
if(login == true) {
res.contentType('application/json');
var data = JSON.stringify('your_url') // im not sure if you can use relative path here
res.header('Content-Length', data.length);
res.end(data);
}

Related

How to verify recaptcha in server call?

SITUATION:
I used to check my recaptcha with a simple form submit with POST to "/login".
I need to change my implementation for security reasons and would like to do something like:
1) Jquery form submit.
2) Make call to server to call verify recaptcha on the server.
3) Receive response without reloading page.
4) Accept login request or not based on response.
QUESTION:
It looks like I could make an AJAX request ? But I don't know how.
CLIENT CODE:
<div class ="containerMargins">
<h1 class = "authTitle">Login</h1>
<form id="loginForm">
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" name="email" id="loginEmail" placeholder="You can't forget it :)" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" id="loginPassword" placeholder="We hope you didn't forget it ^^" required minlength="12">
</div>
<div class="g-recaptcha" data-sitekey="6LcRrxMUAAAAANx-AXSdRLAo4Pyqfqg-1vuPSJ5c"></div>
<button class="btn btn-default" id="loginButton">Submit</button> <span class="userLinks">
<a class="logLinks" href="/users/register">Register</a>Password?</span>
</form>
</div>
</div>
<% include ../partials/indexScripts %>
<script>
$("#loginForm").submit(function(e) {
e.preventDefault();
var email = $("#loginEmail").val();
var password = $("#loginPassword").val();
// WOULD LIKE TO MAKE SERVER CALL HERE TO CHECK RECAPTCHA BUT I DONT KNOW HOW
$this = $(this);
$.ajax({
type: "POST",
url: "users/register",
data: $this.serialize()
}).done(function(data) {
if (successfulRecaptcha) {
firebase.auth().signInWithEmailAndPassword(email, password ).then( authData => {
}
else {
console.log("You are a robot!");
}
SERVER CODE:
router.post('/login', function(req, res, next) {
verifyRecaptcha(req.body["g-recaptcha-response"], function(success) {
if (success) {
} else {
}
});
});
I found the solution :
FRONT END:
$this = $(this);
$.ajax({
type: "POST",
url: "login",
data: $this.serialize()
}).done(function(data) {
if (data == true) {
BACKEND:
router.post('/login', function(req, res, next) {
verifyRecaptcha(req.body["g-recaptcha-response"], function(success) {
if (success) {
res.send(true);
} else {
res.send(false);
}
});
});

jquery ajax api post method error with nodejs and express server ... 405: unable to load resource

I am trying to login a new user and post that instance to SQL using express. On the front end I am getting a server 405 error with my jquery ajax post request.
jquery
the front end request to the backend
i am getting 405 server error
$("#form").on('submit', function(e){
e.preventDefault();
var user = {
email: $('loginemail').val(),
password: $('loginpassword').val()
};
$.ajax({
method: "POST",
url: "/signup",
data: user
}).then(function(res){
if(res.user){
console.log("boom");
window.location.href = "./profile-page/index.html";
}
});
express router
the controller file routed to the /signup post method
using express and sequelize
create : function(req,res){
User.create(req.body).then(function(result,error){
if(error){
console.log(error);
res.send(error);
}else{
res.send("./public/profile-page/index.html");
}
});
}
this is the html section of the code
<form id="form" >
<div class="container">
<h1>Sign Up</h1>
<label><b>Email</b></label>
<input id="loginemail" type="text" placeholder="Enter
Email"name="email" required>
<br>
<label><b>Password</b></label>
<input id="loginpassword" type="password" placeholder="Enter
Password" name="password" required>
<br>

I keep getting HttpGet Again and Again

My problem is i have a login page, it is very simple, I am getting the username and password. I am controlling it at server side. I am using javascript delivering data View to Controller. But the problem is it always sends me to same page. I am always entering the userName and password, but the data even when its correct, there is not a redirect.
My View Code,
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Yelken Otel Rezervasyon Kontrol Sistemi</title>
<script type="text/javascript">
function Login() {
var userName = document.getElementById("userName").value;
var password = document.getElementById("password").value;
$.ajax({
type: 'POST',
url: '/RezervasyonTalepleri/Giris',
dataType: 'json',
data: {
'userName': userName,
'password': password
},
success: function (msg) {
location.href = '/RezervasyonTalepleri/Denetim';
}
});
};
</script>
</head>
<body>
<div class="login-page">
<div class="form">
<form class="login-form">
<input id="userName" type="text" placeholder="username" />
<input id="password" type="password" placeholder="password" />
<button id="btnLogin" onclick="Login()" >login</button>
</form>
</div>
</div>
</body>
</html>
My Controller Code,
[HttpGet]
public ActionResult Giris()
{
return View();
}
[HttpPost]
public ActionResult Giris(string userName, string password)
{
if(userName=="admin" && password == "123")
{
return Json(new { status = "success" });
}
else
{
return JavaScript("Yanlış Kullanıcı Adı veya Şifre Girdiniz.");
}
}
I expect that when i enter the right userName and password, it should redirect me to /RezervasyonTalepleri/Denetim but it always redirects me to /RezervasyonTalepleri/Giris.
You need jQuery library for example included it as below:
<title>Yelken Otel Rezervasyon Kontrol Sistemi</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript"> ...
If I understood your problem correctly,
The success function is called when the invocation of the Giris Action was successful and not when you return success as status.
In your example, you need to check if msg.status is equal to success and you are ready to go.
So your success function would be
success: function (msg) {
if (msg.status === 'success')
{
location.href = '/RezervasyonTalepleri/Denetim';
}
}

Sending Form Data to Node Server

I am trying to send some form data to an endpoint.
Here's my client side code:
<form name="form" action="http://localhost:8080/geodata" method="post">
<label for="minlat"> MinLat: </label>
<input type="text" name="MinLat" value="0"><br>
<label for="maxlat"> MaxLat: </label>
<input type="text" name="MaxLat" value="1"><br>
<label for="minlong"> MinLong: </label>
<input type="text" name="MinLong" value="0"><br>
<label for="maxlong"> MaxLong: </label>
<input type="text" name="MaxLong" value="1"><br>
<button type="submit" class="btn btn-success"> Submit <span class="fa fa-arrow-right"></span></button>
</form>
<script>
$(document).ready(function() {
$("#form")
.submit(function(event) {
var formData = {
'minLat' : $('input[name=MinLat]').val(),
'maxLat' : $('input[name=MaxLat]').val(),
'minLong' : $('input[name=MinLong]').val(),
'maxLong' : $('input[name=MaxLong]').val()
};
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
dataType: 'json',
processData: false,
type: 'POST',
}).done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
I have an enpoint on the server side code (express.js):
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
// Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
app.post("/geodata", function(req, res) {
console.log(req.body);
res.send("hi");
});
I wish to send this form data to the endpoint /geodata, and use that data to send a result back to the client side. First of all, when I hit submit, I get an empty {} in my terminal (which is the server side request.body). I was expecting form values in this request.body but don't receive them. How do I make sure my form values are being sent?
Secondly, res.send("hi") re-directs my initial page to a new page and prints "hi" there. Since I had made an ajax call, shouldn't the response just be logged and the webpage stays on the initial page?
Change the form action to '/geodata'(the endpoint)
also you dont need to make a ajax request as HTML5 forms will perform the request itself if a tag() is pressed/clicked.
after you click summit your page will become what ever response that is sent back from '/geodata' route
and req.body will return a object that represents the form data
dataType: 'json' means you are expecting json data from the server. remove dataType, and add this
data : JSON.stringify(formData),
contentType: 'application/json',
contentType would be the type of data you are sending to the server.

How to trigger javascript on node events?

I have a standard login page. When the database validates the credentials entered by the user I want to make changes to the page, example: create element saying "Login Successful", using a static javascript file. How do I communicate to a static javascript file that the login was successful thus triggering the changes? I'm using Parse right now for my database.
html:
<form class="form" method="post">
<div>
<label>Username:</label>
<input class="form-control" id="username" type="text" name="username">
</div>
<div>
<label>Password:</label>
<input class="form-control" id="password" type="password" name="password">
</div>
<input class="btn btn-custom" type="submit" id="loginSubmit" name="loginSubmit" value="Submit">
</form>
Node with Express and Parse:
login.post('/login', function (req, res) {
Parse.User.logIn(req.body.username, req.body.password, {
success: function(user) {
console.log("Login Successful!");
res.redirect('/');
},
error: function(user, error) {
res.redirect('/login');
console.log("Login Unsuccessful! " + error.message);
}
});
});
The solution was using jQuery's Ajax method.
$('#loginSubmit').on('click', function () {
$.ajax({
//...
success: function(data, textStatus, xhr) {
console.log(xhr.status);
if (xhr.status === 200) {
console.log("fun time?");
$('body').css("background-color", "yellow");
}
},
complete: function(xhr, textStatus) {
console.log(xhr.status);
}
});
});

Categories

Resources