DataBase connection when clicked - javascript

I'm learning how to make websites and I ran into a problem that I can't solve, I hope you can explain it to me. I have set up and created a database (I am sure it works and I have tried to use it), but I do not know how to use it in a real project. I have a small page with a few fields and a button, and when I click on it, I connect to the database (I'll add some functions later). But I can't figure out how to do that. Can you help me?
Here's my HTML code:
<div class="login-card-container">
<div class="login-card">
<div class="login-card-header">
<h1 style="font-size: 23px">Tell about yourself</h1>
</div>
<br>
<form class="login-card-form">
<div class="form-item">
<input type="text" placeholder="Name" id="text1"
autofocus required>
</div>
<div class="form-item">
<span class="form-item-icon material-symbols-rounded">lock</span>
<input type="text" placeholder="School number" id="text2"
required>
</div>
<button type="submit" id="btn_save">Save</button>
</form>
</div>
</div>
<script>
let btn = document.getElementById('btn_save')
btn.addEventListener('click', function(event) {
//here I need to interact with my DB
})
</script>
That's how I connect to my DB:
const conn = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'pocketsage',
password: ''
})
await conn.connect( err=> {
if (err) {
console.log(err)
return err
} else {
console.log('DATABASE ----- CONNECTED SUCCESSFULLY')
}
})
await conn.end(err=> {
if (err) {
console.log(err)
return err
} else {
console.log('DATABASE ----- DISCONNECTED SUCCESSFULLY')
window.location.href = 'http://localhost:3002/pocketsage'
}
})
}

Related

Why will my table not display when search button is clicked?

I can not get the table to display when the search button is clicked using JavaScript. not sure why, can someone please help? Code snippets below and actual repos and site linked below as well.
Here is GitHub repo so that you can see the entire site if you wish:
https://github.com/Chad1515/pets-r-us
Here is the site deployed on heroku:
https://oneal-pets-r-us.herokuapp.com/
//trying to display appointments on my appointment page
app.get('/my-appointments', (req, res) => {
res.render('my-appointments', {
title: 'My Appointments',
})
})
app.get('/api/appointments/:email', async(req, res, next) => {
Appointment.find({'email': req.params.email}, function(err, appointments) {
if (err) {
console.log(err);
next(err);
} else {
res.json(Appointment);
}
})
})
<!--form inputs and card for appointments-->
<section>
<div class="card2">
<p>My Appointments</p>
<hr class="third">
<div class="form">
<div class="form-field">
<label for="email">email</label><br />
<input type="text" class="input" name="email" id="email" required>
</div>
<div class="form-field">
<input type="submit" value="Search" id="search" class="btn">
</div>
<div id="appointments"></div>
</div>
</div>
</section>
<script>
document.getElementById('search').onclick = function() {
const email = document.getElementById('email').value;
fetch('/api/appointments/' + email)
.then(res => res.json())
.then(data => {
let tableString = `<br /><br /><h4 style="font-size: 32px; text-align: center; padding-bottom: 10px;">
My Appointments</h4><table id="appointments" class="table"><tr><th>First name</th><th>Last name</th><th>Email</th><th>Service</th></tr>`;
for (let appointment of data) {
tableString += `<tr><td>${appointment.firstName}</td><td>${appointment.lastName}</td><td>${appointment.email}</td><td>${appointment.service}</td></tr>`;
}
tableString += `</table>`;
document.getElementById('appointments').innerHTML = tableString;
});
}
</script>
It looks like you are responding with the Appointment model object instead of the appointments documents. Try this instead:
app.get('/api/appointments/:email', async(req, res, next) => {
Appointment.find({'email': req.params.email}, function(err, appointments) {
if (err) {
console.log(err);
next(err);
} else {
// Respond with the appointments documents instead of the Appointment model
res.json(appointments);
}
})
})

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

enctype="multipart/form-data" always return null input but it is a must for multer to work how can we fix this?

Good day everyone,
I want to use this multer framework for my input which has an image to be uploaded to my project file directory and sending the image file name to mysql database but enctype="multipart/form-data" returns my inputs to null and enctype="multipart/form-data" is a must for multer to work. I can't find relevant issue like mine I need your help guys.
music_index.ejs
<form class="add-music-form" action="/save" method="POST" enctype="multipart/form-data">
<div class="form-group">
<div class="song-featured-image">
<input style="display: none;" type="file" accept="image/*" id="file" name="featured_img" onchange="loadFile(event)" required>
<img id="output" class="image-preview" width="130" src="/img/rock-on.jpg" />
<label for="file" class="attach_file" style="cursor: pointer">
<i class="material-icons">attach_file</i></label>
</div>
</div>
<div class="mt-3">
<button type="submit" class="btn btn-primary">Submit</button>
<a onclick="cancel()" class="btn btn-default">Cancel</a>
</div>
</form>
app.js
app.post('/save', (req, res) => {
upload(req, res, (err) => {
if(err){
res.render('music_index', {
msg: err
});
} else {
if(req.file == undefined){
res.render('music_index', {
msg: 'Error: No File Selected!'
});
} else {
res.render('music_index', {
msg: 'File Uploaded!',
file: `uploads/${req.file.filename}`
});
}
}
});
let data = {
featured_img: req.body.featured_img,
title: req.body.title,
band_name: req.body.band_name,
audio: req.body.audio
};
let sql ="INSERT INTO music SET ?";
let query = connection.query(sql, data,(err, results) => {
if(err) throw err;
res.redirect('/');
});
});
opinion
try req.body-> req.file
let data = {
featured_img: req.file.featured_img,
title: req.file.title,
band_name: req.file.band_name,
audio: req.file.audio
};

Html - Javascript: Mysql doesnt saving data in database

i just have a register button in my html as follows, which calls the register() function from the insert.js file. When i run alone the insert.js script it writes data to my database. The problem is that when i combine it(the js script) with this html code, it writes nothing. What im doing wrong?
<form method="post">
<div class="inputs">
<div class="input">
<input placeholder="Email" name="email" type="text">
<img src="img/mail.svg">
</div>
<div class="input">
<input placeholder="username" name="username" type="text">
<img src="img/user.svg">
</div>
<div class="input">
<input placeholder="password" name = "password" type="password">
<img src="img/pass.svg">
</div>
</div>
<button onclick="register()" >Register</button>
</form>
<script src="insert.js"></script>
my insert.js file
function register()
{
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "assessment"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO users (username, password) VALUES ('james', 'bond007')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
}
Well, it seems to me that js file its node which is back-end, installed on a server and the HTML it's front-end which runs on the user machine, that js it's fine but should be accessible for the HTML, the front, whoever uses your application, through an endpoint which you can do on node, but I could be wrong if you are using some kind of framework...

express validator how to get req.validationErrors() to front side?

Hello and thanks for reading. I try to use express-validator. It works fine and block the post if for instance the name input is empty. But I don't know how I can get the error message on the front side. I have tried lot of things without success. Hope somebody can help and sorry for the size of the message. Here is a link to the doc of express validator if it can help ( https://express-validator.github.io/docs/ )
My code...
I have create a basic form:
<form id="sign-in">
<div class="form-group">
<label for="nom">name</label>
<input id="name" type="text" class="form-control" placeholder="name" autocomplete="family-name">
</div>
<div class="form-group">
<label for="username">username</label>
<input id="username" type="text" class="form-control" placeholder="username" autocomplete="given-name">
</div>
<div class="form-group">
<label for="email">email</label>
<input id="email" class="form-control" type="email" placeholder="monemail#gmail.com" autocomplete="email"></input>
</div>
<div class="form-group">
<label for="password">password</label>
<input id="password" class="form-control" type="password" autocomplete="current-password"></input>
</div>
<div class="form-group">
<label for="confirm-password">confirm-password</label>
<input id="confirm-password" class="form-control" type="password" autocomplete="current-password"></input>
</div>
<button type="submit" class="btn btn-primary">sign-in</button>
</form>
</section>
<footer>
</footer>
<script type="module" src="/js/sign-in.js"></script>
Then I do my fetch on the file sign-in.js:
document.getElementById('sign-in').addEventListener('submit', event => {
event.preventDefault()
const name = document.getElementById('name').value
const username = document.getElementById('username').value
...
// Use fetch to post data into the DB
window.fetch(`${config.serverHost}/sign-in`, {
method: 'post',
body: JSON.stringify({
name,
username,
...
})
}).then((res, errors) => {
if (res.status === 200) {
window.parent.location.reload()
} else if (res.status === 422) {
DONT KNOW WHAT TO DO TO GET MY ERROR MESSAGE
}
})
})
And finaly the server side:
app.post('/sign-in', (req, res, next) => {
// Start express validator //
req.checkBody('name', 'Please write your name').notEmpty()
req.checkBody('username', 'Please write your name').notEmpty()
...
const errors = req.validationErrors()
if (errors) {
SEND ME BACK MY ERROR MESSAGE
} else {
this part works fine, thank you
}
})
You have two options here depending on how your client is setup:
Use either express-flash or connect-flash to send errors back to your view. See this for the differences.
Use res.json to send back the errors object you created from validationErrors(). Be sure to set the appropriate HTTP status as well.
As I found the solution I post it, it may be useful for others.
Here is the sign-in.js file:
.then(res => {
if (res.status !== 200) {
res.json()
.then(res => errorsMessages.innerHTML = res.map(e => `<p>${e.msg}</p>`).join(''))
} else {
window.parent.location.reload()
}
})
And the code for the server:
const errors = req.validationErrors()
if (errors) {
res.status(422).json(errors)
} else {...}
Thank you Francisco for your help.

Categories

Resources