cannot post login form html node js - javascript

I have seen the same problem a few times on stack, but not one that seems to help me. I have a register form with a submit button that I am trying to get to submit data to MySQL and take me to the login page using node js. It successfully submits data, but will say Cannot POST / loginform.html.
Here is my index.html (register form)
<form target = "_blank" method = "post" action="//localhost:3000/LoginForm.html" onsubmit = "return validationRedirect();">
<div class="container">
<h1>Register</h1>
<p>Please fill out this form to create an account for BAH University.</p>
<hr>
<img style="float: right; margin: 40px 20px 20px 20px;" src="views/photos/furman.jpg" width="770" height="310" border = "4" />
<img style="float: right; margin: -24px 20px 0px 0px;" src="views/photos/furman1.jpg" width="770" height="310" border = "4" />
<div class="relative"><em><i>Committed to Excellence</i></em></div>
<label for="username"><b>Username</b></label>
<br>
<input type="text" style="width: 600px" placeholder="Enter Username" name="Username" required>
<br>
<label for="psw"><b>Password</b></label>
<br>
<input type="password" style="width: 600px" placeholder="Enter Password" name="Password" required>
<br>
<label for="pswrepeat"><b>Repeat Password</b></label>
<br>
<input type="password" style="width: 600px" placeholder="Repeat Password" name="Passwordrpt" required>
<br>
<label for="lastName"><b>Last Name</b></label>
<br>
<input type="text" style="width: 600px" placeholder="Last Name" name="LastName" required>
<br>
<label for="firstName"><b>First Name</b></label>
<br>
<input type="text" style="width: 600px" placeholder="First Name" name="FirstName" required>
<br>
<label for="address"><b>Address</b></label>
<br>
<input type="text" style="width: 600px" placeholder="Address" name="Address">
<br>
<label for="email"><b>Email</b></label>
<br>
<input type="text" style="width: 600px" placeholder="Email" name="Email" required>
<br>
<label for="phone"><b>Phone</b></label>
<br>
<input type="text" style="width: 600px" placeholder="Phone" name="Phone" required>
<hr>
<input name = "submit" type = "submit" value = "Register" class = "savebtn">
<!--<a><input type ="button" value = "Login" class = "registerbtn" onclick = "window.location.href ='LoginForm.html'"></a>-->
</div>
</form>
</body>
</html>
And my LoginForm.html
<form action="/LoginForm" method = "post">
<div class="container">
<h1>Login</h1>
<img src="views/photos/furman.jpg" alt="BAH" style="float: left; margin: 10px -30px 45px 20px; width:
708px;height:365px;" border = "4">
<img src="views/photos/furman1.jpg" alt="BAH" style="float: left; margin: 10px -30px 45px 20px; width:
708px;height:365px;" border = "4">
</br></br></br>
<label for="username"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<input type = "submit" value = "Login" class = "newlogbtn">
<a><input type="button" class="newuserbtn" value = "New User" button onclick = "window.location.href ='index.html'"></a>
</div>
<div class="container" style="background-color: white">
<bgcolor = "black"></bgcolor>
</div>
</form>
</body>
</html>
index.js
var express = require('express');
var app = express();
var router = express.Router();
var mysql = require('mysql');
var http = require('http');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: ""
})
app.use(express.static(__dirname + '/public')); //for css and photos directory
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/LoginForm.html', function (req, res) {
res.sendFile(__dirname + '/LoginForm.html');
});
app.post('/RegisterForm', function (req, res) {
let name = req.body.Username + ' ' + req.body.Password + ' ' + req.body.Passwordrpt + ' ' + req.body.FirstName + ' ' + req.body.LastName + ' ' + req.body.Address + ' ' + req.body.Email + ' ' + req.body.Phone;
res.send(name + ' Submitted Successfully!');
//router.post('/registerform', function(req, res, next) {
con.connect(function(err) {
if (err) throw err;
console.log("connected");
var sql = "INSERT INTO persontable (Username, Password, LastName, FirstName, Address, Email, Phone)VALUES('"+req.body.Username+"','"+req.body.Password+"', '"+req.body.LastName+"', '"+req.body.FirstName+"', '"+req.body.Address+"', '"+req.body.Email+"', '"+req.body.Phone+"')";
con.query(sql, function(err, result) {
if(err) throw err;
console.log("Register information saved.");
});
});
//})
});
var server = app.listen(3000, function () {
console.log('Node server is running on port 3000..');
});
Thanks in advance for the help.

The method that worked for me was to use app.route method
https://expressjs.com/en/guide/routing.html
Eg:
app.route("url")
.get(function())
.post(function());
refer the documentation for more details on route

action="//localhost:3000/LoginForm.html"
You are trying to post to LoginForm.html.
Cannot POST / loginform.html
The error message confirms this
app.get('/LoginForm.html', function (req, res) {
You have a GET handler for that URL.
app.post('/RegisterForm', function (req, res) {
The only POST handler you have is for a different URL.
The route you are POSTing to needs to exist!

In your index.html there is :
action="//localhost:3000/LoginForm.html"
However in your server.js, your doing a get not a post on LoginForm.html
app.get('/LoginForm.html', function (req, res) {
res.sendFile(__dirname + '/LoginForm.html');
});

your error is simply in your registration form, you target the file LoginForm.html, not your RegisterForm action. If you change:
<form target = "_blank" method = "post" action="//localhost:3000/LoginForm.html" onsubmit = "return validationRedirect();">
Into
<form target = "_blank" method = "post" action="//localhost:3000/RegisterForm" onsubmit = "return validationRedirect();">
You will get a post body in your requesthandler.
:

You need to this:
app.get('/LoginForm.html', function (req, res) {
res.sendFile(__dirname + '/LoginForm.html');
});

Related

What is causing the type error in my code?

I am trying to console.log the input in this sign up form but every time i fill the details and the submit the form then it shows the following error
TypeError: Cannot read properties of undefined (reading 'fName')
Kindly let me know the error in my code.
<form action="/" method="POST">
<img class="mb-4" src="images/mail.jpg" alt="" width="72" height="57">
<h1 class="h3 mb-3 fw-normal">Signup the Newsletter</h1>
<div class="form-floating">
<input type="text" name="fName" class="form-control top" placeholder="First Name">
</div>
<div class="form-floating">
<input type="text" name="lName" class="form-control middle" placeholder="Last Name">
</div>
<div class="form-floating">
<input type="email" name="email" class="form-control bottom" placeholder="name#example.com">
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
<p class="mt-5 mb-3 text-muted">Follow me</p>
</form>
// const https = require("https");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended:true}));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.post("/", function(res, req){
var firstName = req.body.fName;
var middleName = req.body.lName;
var eMail = req.body.email;
console.log(firstName, middleName, eMail);
});
app.listen(3000, function() {
console.log("Server is running on Port 3000");
}); ```
I found these errors in your code, check them and it will work fine.
app.use("/public", express.static(path.join(__dirname, 'public'))); // use this for defining your public folder (and don't forget to import path module above).
app.post("/", function(req, res, next){
var firstName = req.body.fName;
var middleName = req.body.lName;
var eMail = req.body.email;
console.log(firstName, middleName, eMail);
});
Here as you can see in the callback function we get three parameters first will be the request object, second will be the response object and third is optional next object.
But in your case you are reading it from response object but it should be from request.
Thanks

Login and Register on the same Page nodejs

Hi guys I am currently creating a website where the login and register is on the same page (for design reasons) I have also tried around but somehow I always get into an infinitely long loading loop.
Folder structure:
The code I have currently divided as follows:
routes/auth.js:
const express = require('express');
const authController = require('../controllers/auth');
const router = express.Router();
router.post('/register', authController.register);
router.post('/register', authController.login);
module.exports = router;
and controllers/auth.js:
const mysql = require("mysql");
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE
});
exports.register = (req, res) => {
console.log(req.body);
const { name, email, password, passwordConfirm } = req.body;
let hashedPassword = bcrypt.hash(password, 10);
console.log(hashedPassword);
db.query('SELECT email from users WHERE email = ?', [email], async(error, results) => {
if (error) {
console.log(error);
}
if (results.length > 0) {
return res.render('message/emailerror');
} else if (password !== passwordConfirm) {
return res.render('message/pwderror');
}
let hashedPassword = await bcrypt.hash(password, 10);
console.log(hashedPassword);
db.query('INSERT INTO users SET ?', { name: name, email: email, password: hashedPassword }, (error, results) => {
if (error) {
console.log(error);
} else {
console.log(results);
console.log('+++++++++++ User registered ++++++++++')
//return res.render('register', {
// message: 'User registered'
//});
}
});
});
}
//to login the user
exports.login = async (req, res) => {
try {
const {emaillogin, passwordlogin} = req.body;
if(!emaillogin || !passwordlogin) {
return res.status(400).render('register', {
message: 'Pls provide something'
});
}
} catch (error) {
console.log(error);
}
}
and the register.hbs where i have the html code:
Login Form:
<div id="login">
<h1 class="loginh1 transform2">Willkommen</h1>
<form class="form transform3" action="/auth/register" method="POST">
<div class="input-container">
<label class="label" for="email"><img src="../img/ETCO-img/icons/mail.svg" height="25px"> <span
style="margin-left:25px;"></span></label>
<input placeholder="example#gmail.com" class="input" type="email" id="emaillogin" name="emaillogin">
</div><br>
<div class="input-container">
<label class="label" for="password"><img src="../img/ETCO-img/icons/lock.svg" height="25px"> <span
style="margin-left:25px;"></span></label>
<input placeholder="Passwort" class="input" type="password" id="passwordlogin" name="passwordlogin">
</div>
<div class="input-container">
<input type="hidden" name="formType" value="signin">
</div>
</form>
<button type="submit" class="bnlogin transform4">LOGIN</button>
</div>
Register Form:
<div class="registerarea transform7">
<h1 class="registerh1 ">Join us</h1>
<form class="formregister" action="/auth/register" method="POST">
<div class="input-container">
<label class="label" for="name"><img src="../img/ETCO-img/icons/user.svg" height="30px"> <span
style="margin-left:30px;"></span></label>
<input placeholder="Your Name" class="input" type="text" id="name" name="name">
</div>
<div class="input-container">
<label class="label" for="email"><img src="../img/ETCO-img/icons/mail.svg" height="25px"> <span
style="margin-left:25px;"></span></label>
<input placeholder="example#gmail.com" class="input" type="email" id="email" name="email">
</div>
<div class="input-container">
<label class="label" for="password"><img src="../img/ETCO-img/icons/lock.svg" height="25px"> <span
style="margin-left:25px;"></span></label>
<input placeholder="Passwort" class="input" type="password" id="password" name="password">
</div>
<div class="input-container">
<label class="label" for="passwordConfirm"><img src="../img/ETCO-img/icons/lock.svg" height="25px">
<span style="margin-left:25px;"></span></label>
<input placeholder="Passwort Bestätigen" class="input" type="password" id="passwordConfirm"
name="passwordConfirm">
</div>
<div class="input-container">
<input type="hidden" name="formType" value="signup">
</div>
<button type="submit" class="btnregister">Lets go</button>
</form>
So, I hope that someone of you can help me. That would be really great. Thanks in advance and best regards :D

Hey I don't know where to start when inserting data into MySql from html form using node.js

I just want to know where to start with getting my html page to work with my back end code and database. I want to insert information into my table with a basic html login page but all i found were confusing sources, maybe i suck at googling but was wondering if someone can help telling me where i should start and what else i need to learn in order to achieve this,
The code below is what i managed to learn and implement.
var http = require('http');
var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var url = require('url');
var pages = require('html-pages');
const css = fs.readFileSync(`${__dirname}/public/art.css`, 'utf-8');
const htmlLogin = fs.readFileSync(`${__dirname}/login.html`, 'utf-8');
const htmlSignUp = fs.readFileSync(`${__dirname}/signup.html`, 'utf-8');
//static files for login
app.use('/login', express.static('./public'));
//
app.get('/login', function(req,res,next) {
res.writeHead(200, {'Content-Type' :'text/html'});
res.write(htmlLogin);
next();
}).listen(3000);
app.get("/signup", function(req,res, next) {
res.writeHead(200, {'Content-Type':'text/html'});
res.write(htmlSignUp);
});
and here is my html page
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<link href="./signup.js">
</head>
<body>
<div class="signupBox">
<h1 id="signUp">Sign Up!</h1>
<div>
<input text="text" placeholder="First Name" name="" value="">
</div>
<div>
<input text=text" placeholder="Last Name" name="Last Name" value="">
</div>
<div>
<input text="text" placeholder="Email" name="Email" value="">
</div>
<div>
<input text="text" placeholder="Password" name="Password" value="">
</div>
<input id="submit" type="button" name="" value="Sign In">
</div>
</body>
</html>
Learning how to back end with node.js and mysql just got stuck in knowing how to do this task,
var express = require('express');
var app = express();
var session = require('express-session');
var bodyParser = require('body-parser');
var path = require('path');
var http = require('http');
var sql = require('mysql');
var fs = require('fs');
var url = require('url');
var myDB = sql.createConnection({
//properties...
host: 'localhost',
user: 'root',
password: '',
database: 'sampleDB'
});
myDB.connect(function(err) {
if (err) {
console.log('There is an error');
} else {
console.log("Connected to Database");
}
});
As what I am seeing from your code, you already setup login and signup page, it it's working than now you now to save signup data you can create new route like
app.post("/register", function(req,res, next) {
console.log('request data', req.body) // you will get signup for data here.
});
and in signup for you need to add action like -
<form method="post" action="localhost:3000/register">
<h1 id="signUp">Sign Up!</h1>
<div>
<input text="text" placeholder="First Name" name="" value="">
</div>
<div>
<input text=text" placeholder="Last Name" name="Last Name" value="">
</div>
<div>
<input text="text" placeholder="Email" name="Email" value="">
</div>
<div>
<input text="text" placeholder="Password" name="Password" value="">
</div>
<input id="submit" type="button" name="" value="Sign In">
</form>
you can do same with login verification, send login detail as in below route -
app.post("/checkLogin", function(req,res, next) {
console.log('request data', req.body) // you will get login detail here.
});
Hop this help.
Update html:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<link href="./signup.js">
</head>
<body>
<div class="signupBox">
<h1 id="signUp">Sign Up!</h1>
<form action="signup" method="POST">
<!-- it's important to define name="xx" here otherwise you'll get 'undefined' value in server side -->
<div> <input type="text" placeholder="First Name" name="firstname"> </div>
<div> <input type="text" placeholder="Last Name" name="lastname"> </div>
<div> <input type="text" placeholder="Email" name="email"> </div>
<div> <input type="password" placeholder="Password" name="password"> </div>
<input id="submit" type="button" name="" value="Sign Up">
</form>
</div>
</body>
</html>
Add this code in server side:
app.post ("/signup", function(req, res) {
// get info from form
var firstname = request.body.firstname;
var lastname = request.body.lastname;
var email = request.body.email;
var password = request.body.password;
var adduserquery = "INSERT INTO `myTable` (`firstname`,`lastname`,`email`,`password`) VALUES ('" + firstname + "', '" + lastname + "', '" + email + "', '" + password + "')";
if (email) {
// check if e-mail already exists
myDB.query('SELECT * FROM `myTable` WHERE email = ?', [email], function(error, results, fields) {
if (results.length > 0) {
response.send('This e-mail is already registered!' );
} else {
// execute query to insert data
myDB.query(adduserquery, (err, result) => {
if (err) {
return response.status(500).send(err);
}
// if insert is successful, return you to homepage
response.redirect('/home');
});
}
});
}
}
}
Thats great you have already added the express module , i woud suggest try adding form tag and give the action to the form tag , on which you want to hit eg /signup and change your input type button to submit this will workout .
<div class="signupBox">
<form action='/signup'>
<h1 id="signUp">Sign Up!</h1>
<div>
<input text="text" placeholder="First Name" name="" value="">
</div>
<div>
<input text=text" placeholder="Last Name" name="Last Name" value="">
</div>
<div>
<input text="text" placeholder="Email" name="Email" value="">
</div>
<div>
<input text="text" placeholder="Password" name="Password" value="">
</div>
<input id="submit" type="button" name="" value="Sign In">
</form>
</div>
Now if you click on submit the data can be getable inside the /signup route you have created using the req.body.NAME_VALE , once you got the value you can insert it into the database .

i am not able to fetch data from html controls using get method in nodejs and mongodb

problem in code
var userID = req.userid;
var pwd = req.pwd;
console.log("userid = " + userID + "pass = " + pwd);
the console shows values undefined instead of input data
the console shows values undefined instead of input data
I want to take data from an html file and insert into the mongo database using get method. But I am not able to fetch data from the textbox.
Code in nodejs(index.js)
const express = require('express');
const path = require('path');
const bodyparser = require("body-parser");
const mongoose = require('mongoose');
const app = express();
app.use(bodyparser());
app.use(bodyparser.urlencoded({
extended: false
}));
app.use(bodyparser.json());
app.set('port', (process.env.PORT || 1000));
mongoose.connect('mongodb://localhost/TrackDB');
var Schema = new mongoose.Schema({
username: String
, pass: String
});
var users = mongoose.model('users', Schema);
app.get("/register", function (req, res) {
var userID = req.userid;
var pwd = req.pwd;
console.log("userid = " + userID + "pass = " + pwd);
new users({
username: userID
, pass: pwd
}).save(function (err, doc) {
if (err) {
res.json(err);
}
else res.send("Successfully Registerd!");
});
console.log("users = " + users);
});
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, './public/index.html'));
});
app.listen(1000, () => {
console.log("Server Start......");
});
HTML Page (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LOGIN/REGISTER</title>
<style>
#container {
width: 40%;
margin: auto;
border: 1px solid;
padding: 10px;
padding-left: 200px;
border-radius: 10px;
}
</style>
</head>
<body>
<div id="container">
<h1>Register</h1>
<form action="/register">
<div id="register">
<input type="text" name="userid" id="txt_userid" placeholder="Enter user id">
<br>
<input type="password" name="pwd" id="txt_pass" placeholder="Enter password">
<br>
<br>
<button type="submit" id="btn_register">Register</button>
</div>
</form>
<h1>Login</h1>
<form action="/login">
<br>
<br>
<div id="login">
<input type="text" name="user" id="userid" placeholder="Enter user id">
<br>
<br>
<input type="password" name="passw" id="pass" placeholder="Enter password">
<br>
<br>
<button type="submit" id="btn_login">Login</button>
</div>
</form>
<h1 id="msg"></h1> </div>
</body>
</html>
Try this code
var userID =req.query.userid;
var pwd = req.query.pwd
You need to use POST request, and the data won;t be available in req object. Instead it will be available in req.body
Try:
var userID = req.body.userid;
var pwd = req.body.pwd;
console.log("userid = " + userID + "pass = " + pwd);
You have to use app.post method in node.js.
And use method = post.
<form action="/register" method="post">
<div id="register">
<input type="text" name="userid" id="txt_userid" placeholder="Enter user id">
<br>
<input type="password" name="pwd" id="txt_pass" placeholder="Enter password">
<br>
<br>
<button type="submit" id="btn_register">Register</button>
</div>
</form>
Sending data to node uses post, delete, put methods. But if you wish to fetch data back from node you can use .get() method.
I suggest try to print req(i.e console.log(req)). As might be data is stored in req.body.

getting values from a POST method in expressJS

I'm trying to register a user in my application. This is the HTML code:
<form id="registration_form" action="register" onsubmit="return validateForm();" method="post">
Username: <input type="text" id="username" name="user[name]" /><br />
Password: <input type="password" id="password" name="user[pass]" /><br />
Repeat Password: <input type="password" id="password_repeat" name="user[pass]" /><br />
Email: <input type="text" id="email" name="user[email]" /><br />
<button type="submit" value="Register">Register</button>
<div id="error_registration" style="color: red;">
</div>
</form>
What I do in the server is taking the values of name, pass and email.
var express = require('express')
, app = express.createServer(
express.logger(),
express.cookieParser(),
express.session({ secret: 'keyboard cat' })
)
, io = require('socket.io').listen(app)
, mongoose = require('mongoose')
, schemas = require('./schemas')
, Schema = mongoose.Schema;
app.listen(80);
app.configure(function(){
app.use(express.bodyParser());
});
[...]
app.post('/register', function (req, res) {
registerUser(req, function(result){
//do something
var username = req.body.username;
});
});
My question is: why username is always undefined? Am I reading it in the wrong way? How should I then?
Thanks
Your variable is user not username.
Look:
..input type="text" id="username" name="user[name]" ..
Also you can always do console.log(req.body) to see the POST vars in the terminal.

Categories

Resources