I keep getting Error: ER_EMPTY_QUERY: QUERY was empty - javascript

I'm trying to make a register page. When I enter the data that needs to be registered, it shows up on the console followed by Error: ER_EMPTY_QUERY.
I believe the problem is in the controllers/auth.js file but I can't figure it out for some reason. Please help, been stuck on this for the past 2 days.
controllers/auth.js:
const mysql = require('mysql');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'practice'
})
exports.register = (req, res) => {
console.log(req.body)
const {name, email, password, passwordConfirm} = req.body
db.query('SELECT email FROM users WHERE email = ?' [email], async (error, results) => {
if(error) {
console.log(error)
}
if( results.length > 0 ) {
return res.render('register', {
message: 'That email is already is use'
})
} else if( password !== passwordConfirm) {
return res.render('register', {
message: 'Passwords do not match'
})
}
let hashedPassword = await bcrypt.hash(password, 8);
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);
return res.render('register', {
message: 'User registered'
})
}
})
})
}
register.hbs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/styles.css">
<title>Document</title>
</head>
<body>
<nav>
<h4>Node MySQL</h4>
<ul>
<li>Home</li>
<li>Login</li>
<li>register</li>
</ul>
</nav>
<div class="container mt-4">
<div class="card">
<div class="card-header">
Register Form
</div>
<div class="card-body">
<form action="/auth/register" method="POST">
<div class="mb-3">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name">
</div>
<div class="mb-3">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email">
</div>
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<div class="mb-3">
<label for="passwordConfirm">Confirm Password</label>
<input type="password" class="form-control" id="passwordConfirm" name="passwordConfirm">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
{{#if message}}
<h4 class="alert alert-daner mt-4">{{message}}</h4>
{{/if}}
</div>
</body>
</html>

Related

How to transfer image upload from form to backend upload?

I managed to upload an image in form, but i want to save it to backend and then when i call it again using frontend i will b able to save a picture
function code :
addFilm: (title, description, release_year, language_id, rental_duration, rental_rate, length, replacement_cost, rating, special_features, category_id, actors, store_id, callback) => { //1.(1 ~ 3 are places to change code )
var conn = db.getConnection(); // GET CONNECTION TO DB
conn.connect((err) => {
if (err) {
console.log(err);
return callback(err, null);
} else {
console.log('Connected Successfully!');
var SQLstatement = //use backtick to go onto next line
// first insert into film table
`insert into film (title,description,release_year,language_id,rental_duration,rental_rate,length,replacement_cost,rating,special_features)
Values(?,?,?,?,?,?,?,?,?,?)`; // 2.
conn.query(SQLstatement, [title, description, release_year, language_id, rental_duration, rental_rate, length, replacement_cost, rating, special_features], (error, result_id) => { //3.
if (error) {
console.log(error);
return callback(error, null);
}
else {
// second insert into film_category table
var SQLstatement = `insert into film_category (film_id,category_id) Values (?,?)`
conn.query(SQLstatement, [result_id.insertId, category_id], (error, result) => {
if (error) {
console.log(error);
return callback(error, null);
}
else {
console.log(result);
// neeed check actor
console.log(actors);
var SQLstatement = ''
values = []
// add a new actor id with the same film id to the film_actor table
for (var k = 0; k < actors.length; k++) {
if (k == actors.length - 1) {
SQLstatement += `(?,?)`
}
else {
SQLstatement += `(?,?),`
}
// console.log(actors[k])
values.push(actors[k])
values.push(result_id.insertId)
}
var finalSQLstatement = `insert into film_actor (actor_id,film_id) Values ` + SQLstatement
conn.query(finalSQLstatement, values, (error, result) => {
if (error) {
console.log(error);
return callback(error, null);
}
})
console.log(result_id.insertId);
var SQLstatement = //use backtick to go onto next line
// last insert into inventory with same film_id and store_id
`insert into inventory(film_id,store_id) Values(?,?)`; // 2.
conn.query(SQLstatement, [result_id.insertId, store_id], (error, result) => { //3.
conn.end();
if (error) {
console.log(error);
return callback(error, null);
}
else {
console.log(result);
return callback(null, result.insertId);
}
});
}
})
// });
}
});
}
});
},
app.get():
app.get('/view/:filmid',function(req, res){
var filmid = req.params.filmid;
actorDB.getDetails(filmid, function(err, result){
if(!err){
console.log(result);
res.send(result);
}else{
res.status(500).send("Some error");
}
});
});
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Customer</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<nav class="nav">
<a class="nav-link" href="/">Home</a>
<a class="nav-link" href="/users/">All Users</a>
</nav>
<h1>Register a new DVD</h1>
<form id="register-form">
<div class="form-group">
<div class="file-upload w-100">
<form class="image-upload-wrap d-flex justify-content-center align-items-center"
style="height: 240px">
<input class="file-upload-input" type="file" onchange="readImage(this);" accept="image/*"
id="imageFile" />
<div class="drag-text w-100 d-flex flex-column justify-content-center align-items-center">
<div id="imageErr" class="text-danger d-none">
Invalid Image
</div>
<h3>Drag photo here</h3>
<p>— or —</p>
<button class="btn bg-secondary text-white font-weight-bold text-center" type="button"
style="white-space: nowrap; z-index: 1055" id="addImage"
onclick="$('.file-upload-input').trigger( 'click' )">
Choose photo to upload
</button>
</div>
</form>
<div class="file-upload-content">
<img class="file-upload-image" style="border: 1px black solid" src="#" alt="your image"
id="imgPreview" />
</div>
</div>
</div>
<div class="form-group">
<label for="title">title:</label>
<input type="text" class="form-control" id="title" required>
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" class="form-control" id="description" required>
</div>
<div class="form-group">
<label for="release">Release:</label>
<input type="text" class="form-control" id="release" required>
</div>
<div class="form-group">
<label for="lang">Language_id:</label>
<input type="text" class="form-control" id="lang" required>
</div>
<div class="form-group">
<label for="rental_duration">Rental Duration:</label>
<input type="text" class="form-control" id="rental_duration" required>
</div>
<div class="form-group">
<label for="rental_rate">Rental rate:</label>
<input type="text" class="form-control" id="rental_rate" required>
</div>
<div class="form-group">
<label for="length">Length:</label>
<input type="text" class="form-control" id="length" required>
</div>
<div class="form-group">
<label for="replacement_cost">Replacement Cost:</label>
<input type="text" class="form-control" id="replacement_cost" required>
</div>
<div class="form-group">
<label for="rating">Rating:</label>
<input type="text" class="form-control" id="rating" required>
</div>
<div class="form-group">
<label for="special_features">Special Features:</label>
<input type="text" class="form-control" id="special_features" required>
</div>
<div class="form-group">
<label for="category_id">Category ID:</label>
<input type="text" class="form-control" id="category_id" required>
</div>
<div class="form-group">
<label for="actors">Actors:</label>
<input type="text" class="form-control" id="actors" required>
</div>
<div class="form-group">
<label for="store_id">Store_id:</label>
<input type="text" class="form-control" id="store_id" required>
</div>
<button type="submit" class="btn btn-primary">Register</button>
<button type="reset" class="btn btn-primary ml-5">Reset</button>
<button type="button" class="btn btn-primary ml-5" id="Logout">Log Out</button>
<!-- <input type="reset" value="Reset"> -->
</form>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const baseUrl = "http://localhost:8081";
const token = localStorage.getItem("token");
const loggedInUserID = parseInt(localStorage.getItem("loggedInUserID"));
console.log(token, loggedInUserID)
function readImage(fileInput) {
if (fileInput.files && fileInput.files[0]) {
var imgReader = new FileReader();
imgReader.onload = function (event) {
var wrap = document.querySelector(".image-upload-wrap");
if (wrap) {
wrap.classList.add("d-none");
wrap.classList.remove("d-flex");
}
var imgData = event.target.result.split(',')[1];
var postData = { image: imgData };
fetch('/upload-image.php', {
method: 'POST',
body: JSON.stringify(postData),
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
document.getElementById("addImage").style.display = "none";
var imgPreview = document.getElementById("imgPreview");
imgPreview.src = event.target.result;
var content = document.querySelector(".file-upload-content");
content.classList.add("d-flex", "justify-content-center", "align-items-center");
content.classList.remove("d-none");
var btnSave = document.getElementById("save");
if (btnSave.classList.contains("btn-danger")) {
btnSave.classList.toggle("btn-danger");
btnSave.classList.add("btn-primary");
btnSave.innerHTML = "Save as promo picture";
}
};
imgReader.readAsDataURL(fileInput.files[0]);
} else {
removeUpload();
}
}
if (token === null || isNaN(loggedInUserID)) {
window.location.href = "http://localhost:3001/home";
} else {
$("#register-form").submit((event) => {
// prevent page reload
event.preventDefault();
const title = $("#title").val();
const description = $("#description").val();
const release = $("#release").val();
const lang = $("#lang").val();
const rental_duration = $("#rental_duration").val();
const rental_rate = $("#rental_rate").val();
const length = $("#length").val();
const replacement_cost = $("#replacement_cost").val();
const rating = $("#rating").val();
const feature = $("#special_features").val();
const category_id = $("#category_id").val();
const actors = $("#actors").val();
const store_id = $("#store_id").val();
const requestBody = {
title: title,
description: description,
release_year: release,
language_id: lang,
rental_duration: rental_duration,
rental_rate: rental_rate,
length: length,
replacement_cost: replacement_cost,
rating: rating,
special_features: feature,
category_id: category_id,
actors: actors,
store_id: store_id
};
let token = localStorage.getItem("token");
console.log(requestBody);
axios.post(`${baseUrl}/film`, requestBody, { headers: { "Authorization": "Bearer " + token } })
.then((response) => {
console.log(requestBody)
window.location.href = "http://localhost:3001/home";
})
.catch((error) => {
console.log(error);
if (error.response.status === 400) {
alert("Validation failed");
} else {
alert("Something unexpected went wrong.");
}
});
});
$("#Logout").click(function () {
window.localStorage.clear();
localStorage.removeItem("token");
localStorage.removeItem("loggedInUserID");
window.location.assign("http://localhost:3001/login");
});
}
</script>
</body>
</html>
I need help in parsing the data, even now as i try to submit the form it says Cannot read properties of null (reading 'classList')
at imgReader.onload.

Missing Credentials - Node/Express server Passport.js authentification problem with Sequelize ORM

I'm trying to implement an authentication system using Passport.js for my express web server. However I can't let passport.js do his job in any way , could someone explain me why?
Here is my passport-config.js ;
`
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
const database = require('./modules/database')
function initialize(passport, getUserByUsername) {
const authenticateUser = async (username, password, done) => {
const user = await getUserByUsername(username)
if (user == null) {
return done(null, false, { message: 'No user with that username' })
}
try {
if (await bcrypt.compare(password, user.password)) {
return done(null, user)
} else {
return done(null, false, { message: 'Password incorrect' })
}
} catch (e) {
return done(e)
}
}
passport.use(new LocalStrategy({ usernameField: 'username' , passwordField: 'password' }, authenticateUser))
passport.serializeUser((user, done) => done(null, user.username))
passport.deserializeUser((username, done) => {
return done(null, getUserByUsername(username))
})
}
Here is how i initialize it within app.js ;
initializePassport(
passport ,
username => database.User.findOne({where : {username : username}}).then(user => {return user || null})
)
Here is my get and post /login routers;
app.get("/login", function(req, res, next){
beforeEach(req, res)
res.render("login.ejs", {
session: req.session
})
})
app.post('/login' , passport.authenticate('local', {
successRedirect : '/main',
failureRedirect: '/login',
failureFlash : true
}))
I thought I implemented everything properly , maybe passport can't access the username and password? Here is my login.ejs as well;
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="common.css">
<link rel="stylesheet" href="log_sign.css">
</head>
<body>
<%- include("banner.ejs", {}) %>
<div class="col d-flex justify-content-center">
<div class="extra-padding">
<div class="card" style="width: 18rem;">
<div class="card-body">
<h1>Log in</h1>
<% if (messages.error) { %>
<%= messages.error %>
<% } %>
<form action="/login" method="POST">
<div class="form-group">
<label for="username">Username</label>
<input for="username" type="username" class="form-control" id="username" placeholder="Enter username">
</div>
<br>
<div class="form-group">
<label for="password">Password</label>
<input for="password" type="password" class="form-control" id="password" placeholder="Password">
</div>
<a class="nav-item" href="register">Need an account ? Sign in</a>
<div class="col d-flex justify-content-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>

bcryptjs: Error: Illegal arguments: undefined, number

My goal is to put a login and register form on one page. The register already works but I always get this error when logging in.
I have already tried several things and believe that it has something to do with the submit button. because when the login button is pressed, the login function is not even called. Or I think that I have somehow set the routes wrong.
Here is the html code (register.hbs):
<div class="main_content transform8">
<img class="swipe transform" src="img/ETCO-img/swipepattern.svg" height="150%" width="auto">
<img class="secwave transform7" style="filter: drop-shadow(5px 5px 10px rgba(0, 0,0, 0.171));"
src="img/ETCO-img/secwave.svg" height="30%" width="auto">
<img class="logo transform5" src="img/ETCO-img/logoetco.png" height="270px">
<img id="wave" class="wave transform6" style="filter: drop-shadow(5px 5px 10px rgba(0, 0, 0, 0.171));"
src="img/ETCO-img/wave.svg" height="400px" width="auto">
<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="emaillogin"><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>
<div class="input-container">
<label class="label" for="passwordlogin"><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>
<button type="SUBMIT" class="bnlogin transform4">LOGIN</button>
</form>
</div>
<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>
<button type="submit" class="btnregister">Lets go</button>
</form>
{{#if message}}
<h3 class="alert alert-danger mt-4">{{message}}</h3>
{{/if}}
</div>
and the 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 the code of the controller 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 ++++++++++')
//route to other page later on
}
});
});
}
//to login the user
exports.login = async (req, res) => {
console.log('##### Login Versuch gestartet #####');
try {
const {emaillogin, passwordlogin} = req.body;
if(!emaillogin || !passwordlogin) {
console.log('Fehler Versuch es nochmal');
return;
} else{console.log('funktioniert')}
} catch (error) {
console.log(error);
}
}
I hope someone can help me here, because unfortunately I haven't had much to do with node.js.

Not submit data in mongodb database

Here i tried to store form data in my mongodb database(mongodb compass).
but after submit when i check than there are nothing in my database.
when i press sign up button than it's show me just curly brackets.
App.js file(main file)
const express = require("express");
const app = express();
const port = 8081;
require('./db/conn');
const path = require("path");
const hbs = require("hbs");
const register = require("./models/register");
const static_path = path.join(__dirname,"../public");
const template_path = path.join(__dirname,"../templates/views");
const partials_path = path.join(__dirname,"../templates/partials");
app.set("views",template_path);
app.set("view engine","hbs");
hbs.registerPartials(partials_path);
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.get("/",(req,res)=>{
res.render("signup");
})
app.get("/signup",(req,res)=>{
res.render("index");
})
app.get("/register",(req,res)=>{
res.render("register");
})
app.post("/register",async(req,res)=>{
try{
const password = req.body.password;
const cpassword = req.body.cpassword;
if(password===cpassword){
const registerEmployee = new Register({
firstname : req.body.firstname,
lastname : req.body.lastname,
email : req.body.email,
phone : req.body.phone,
age : req.body.age,
password: req.body.password,
})
const registered = await registerEmployee.save();
console.log(registered);
}
else{
res.send("password not matched");
}
res.send(registered);
}catch(error){
res.status(404).send(error)
}
})
app.listen(port,()=>{
console.log("succesfully port");
})
register.js file(here i define mongoose.schema file)
const mongoose = require("mongoose");
const employeeSchema = mongoose.Schema({
firstname :{
type:String,
required:true,
},
lastname:{
type:String,
required:true,
},
email:{
type:String,
required:true,
unique:true,
},
phone:{
type:Number,
required:true,
unique:true,
},
age:{
type:Number,
required:true,
},
password:{
type:String,
required:true,
},
})
const Register = new mongoose.model("register",employeeSchema);
module.exports = Register;
signup.hbs file(html form)
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/signin.css">
<title>Create New Account</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous">
</script>
<div class="signin-form">
<form action="/register" method="POST">
<div class="form-header">
<h2>Sign Up</h2>
<h2>Fill out this form and start chatting with your friends.</h2><br>
</div>
<div class="form-group">
<br>
<lable>firstname</lable>
<input type="text" class="form-control" name="firstname" placeholder="Username" />
</div>
<div class="form-group">
<br>
<lable>lastname</lable>
<input type="text" class="form-control" name="lastname" placeholder="Username" />
</div>
<div class="form-group">
<br>
<lable>email Address</lable>
<input type="text" class="form-control" name="email" placeholder="someone#site.com" />
</div>
<div class="form-group">
<br>
<lable>phone Number</lable>
<input type="text" class="form-control" name="phone" placeholder="contact number" />
</div>
<div class="form-group">
<br>
<lable>Age</lable>
<input type="number" class="form-control" name="age" placeholder="age" />
</div>
<div class="form-group">
<label> Password </label>
<input type="text" class="form-control" name="password" placeholder="password" />
</div>
<div class="form-group">
<label>Confirm Password </label>
<input type="text" class="form-control" name="cpassword" placeholder="confirm password" />
</div>
<input type="checkbox" class="checkbox-inline" /> <label>i accept terms and condition</label>
<div class="form-group">
<button class="btn btn-primary btn-block btn-lg " name="sign_up">Sign_Up</button>
</div>
</form>
<div class="text-center small" style="color:#67428B;"> Already have an Account ?Login </div>
</div>
</body>
</html>
try to put new before mongoose.Schema :
const employeeSchema = new mongoose.Schema
after so much time i solved error successfully, so i think i want to write here
here you can see in app file 7th line
const register = require("./models/register");
and when i enter new data then i use Register instead of register so there are an error.
const registerEmployee = new Register

How to handle button click and how to get the content of input text in node js

I need to get the data entered in the input text. Using document.getElementById, but displays the error: ReferenceError: document is not defined.
That is, I need to click on the button i get all the data that the user entered.
.........................................................................
.........................................................................
.........................................................................
.........................................................................
.........................................................................
.........................................................................
const express = require('express');
const router = express.Router();
const Cookies = require('cookies');
router.get('/', (req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
// console.log(res.headers(['cookie']));
// res.setHeader('Set-Cookie', 'TestHeader=HeaderValue');
const cookies = new Cookies(req, res);
if (req.url === '/favicon.ico') {
res.end();
return;
}
cookies.set('admin', 'true');
console.log(cookies.get('node'));
res.end(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="signUp.js" defer></script>
</head>
<body>
<h1>Sign Up Form</h1>
<form method="POST" action="/sign-up" autocomplete="off">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" required autocomplete="off">
</div>
<div>
<label for="email">Email</label>
<input type="email" name="email" id="email" required autocomplete="off">
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" required autocomplete="off">
</div>
<div>
<label for="password_confirmation">Password again</label>
<input type="password" name="password_confirmation" id="password_confirmation" required autocomplete="off">
</div>
<button id="sign_up_btn">Sign Up</button>
</form>
Sign In
</body>
</html>
`);
const userName = document.getElementById('name');
const userEmail = document.getElementById('email');
const userPassword = document.getElementById('password');
const userData = [userName, userEmail, userPassword];
for (let i = 0; i < userData.length; i += 1) {
console.log(userData[i]);
}
});
router.post('/', (req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.statusCode = 501;
res.end('Not implemented yet!...');
});
module.exports = router;
please place the script before </body>, or in window.onload callback function. Because document object is not created when you call document.getElementById
You've edited your question so allow me to edit my answer:
Your implementation here is incorrect. You are using Express to serve a webpage with a form. In order to evaluate the values of the form, you'll need to decide if you want to do that on the client side or the server side.
Your form looks like a login form, so you'll want to process this on the server side.
const express = require('express');
const router = express.Router();
const Cookies = require('cookies');
const bodyParser = require('body-parser');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded());
router.use(bodyParser.urlencoded({ extended: true }));
router.get('/', (req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
// console.log(res.headers(['cookie']));
// res.setHeader('Set-Cookie', 'TestHeader=HeaderValue');
const cookies = new Cookies(req, res);
if (req.url === '/favicon.ico') {
res.end();
return;
}
cookies.set('admin', 'true');
console.log(cookies.get('node'));
res.end(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="signUp.js" defer></script>
</head>
<body>
<h1>Sign Up Form</h1>
<form method="POST" action="/sign-up" autocomplete="off">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" required autocomplete="off">
</div>
<div>
<label for="email">Email</label>
<input type="email" name="email" id="email" required autocomplete="off">
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" required autocomplete="off">
</div>
<div>
<label for="password_confirmation">Password again</label>
<input type="password" name="password_confirmation" id="password_confirmation" required autocomplete="off">
</div>
<button id="sign_up_btn">Sign Up</button>
</form>
Sign In
</body>
</html>
`);
router.post('/sign-up', (req, res) => {
const { name, email, password } = req.body;
// do stuff with name, email, password
});
});
router.post('/', (req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.statusCode = 501;
res.end('Not implemented yet!...');
});
module.exports = router;
For client side form processing, you could do something like this:
HTML
<form action="#" onsubmit="handleSubmit(this)">
<input type="text" name="foo" value="bar" />
<input type="submit" value="Submit" />
</form>
Javascript
function handleSubmit(e) {
console.log(e.foo.value)
}
Example

Categories