handleChange and onSubmit on javascript vanilla - javascript

i'm working on my very first app : a login/register form with JS/node Js/ Mysql.
I'm trying to connect my form to my database (to collect my users' data into my db) but my code is not working. I didn't use "handleChange" or "onSubmit" functions because i don't use ReactJS framework. Do you guy think it's necessary?
this is my code :
HTML code:
<div class="msg-alerte">message</div>
<form method="post" action="http://localhost:8000/">
<div class="formulaire">
<h1 class="entete">inscription</h1>
<input type="name" placeholder="nom" name="nom" id="nom" autocomplete="off" required>
<input type="email" placeholder="email" name="email" id="email" autocomplete="off" required>
<input type="password" placeholder="mot de passe" name="password" id="password" autocomplete="off" required>
<button class="btn-valider">s'inscrire</button>
Vous avez déjà un compte? Se connecter
</div>
</form>
JS (frontend) :
const username = document.getElementById('name')|| null;
const email = document.getElementById('email');
const password = document.getElementById('password');
const submitBtn = document.querySelector('.btn-valider');
if(username === 0){
}
else{
submitBtn.addEventListener('click', ()=>{
//register-user??
fetch('/', {
method: "post",
headers: new Headers({'Content-Type':'application/json'}),
body: JSON.stringify({
user_name: username,
email: email,
password: password
})
})
console.log(username);
console.log(email);
console.log(password)
.then(res =>res.json())
})
}
js server :
app.post("/",(req,resp)=>{
//insertion d'une donnée
const data={user_name:req.body.user_name,email:req.body.email, password:req.body.password};
let sql="INSERT INTO users (user_name, email, password) VALUES (?,?, ?);";
pool.query(sql,[data],(err,fields)=>{
if(err)console.log("Echec d'enregistrement à BD");
else{
console.log("Enregistrement effectuee");
resp.redirect("/");
}
});
});
THANK YOU FOR YOUR HELP!!!

It looks like the main issue you will want to resolve before you can move forward is with your fetch call in your frontend code. You need to use the then() method on fetch so you can properly parse and read the response. Currently, you are calling .then(res =>res.json()) on a console.log(). This is not valid.
I have made a modification to your event listener function that you can try
submitBtn.addEventListener('click', () => {
fetch('/', {
method: "post",
headers: new Headers({'Content-Type':'application/json'}),
body: JSON.stringify({
user_name: username,
email: email,
password: password
})
})
.then((res) => res.json())
.then((data) => {
// now we can read the response and decide what to do next
console.log(data);
});
})
I'm also seeing some possible syntactical issues in your node js code. Specifically with the request data assignment and the string interpolation on your query string. You could try something like this:
app.post("/", (req, resp) => {
//insertion d'une donnée
const data =[req.body.user_name, req.body.email, req.body.password];
let sql="INSERT INTO users (user_name, email, password) VALUES ($1, $2, $3)";
pool.query(sql, data, (err, fields) => {
if (err) console.log("Echec d'enregistrement à BD");
else {
console.log("Enregistrement effectuee");
resp.redirect("/");
}
});
});
Please comment if you need any further clarification.

Related

fuana database for static hosted sites

so i wrote this code and I am getting no errors in the console
the only error i get from the fauna server is An error occurred while logging in.
also i will change the secret key after this is awnsered for security reasons.
const client = new faunadb.Client({
secret: "fnAE7vAmHdAA1I7LvovMRWnGVVM2_sit_IrKDgnN"
});
async function signUp() {
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
try {
const result = await client.query(
q.Create(
q.Collection("users"),
{
data: {
email,
password
}
}
)
);
alert("Sign up successful! You can now log in.");
} catch (error) {
console.error(error);
alert("An error occurred while signing up.");
}
}
async function login() {
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
try {
const result = await client.query(
q.Get(
q.Match(
q.Index("users_by_email"),
email
)
)
);
if (result.password === password) {
alert("Login successful!");
} else {
alert("Incorrect email or password.");
}
} catch (error) {
console.error(error);
alert("An error occurred while logging in.");
}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/faunadb"></script>
<script></script>
</head>
<body>
<h1>Sign Up</h1>
<form>
<label for="email">Email:</label>
<input type="email" id="email" required>
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" required>
<br><br>
<button type="button" onclick="signUp()">Sign Up</button>
</form>
<h1>Login</h1>
<form>
<label for="email">Email:</label>
<input type="email" id="email" required>
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" required>
<br><br>
<button type="button" onclick="login()">Login</button>
</form>
</body>
</html>
I've tried looking for errors in thr java script and tried playing around
with the fauna database itself
IMPORTANT
note about credentials in Fauna: using Fauna's built in Credentials support means you don't store the actual password, only the hashed password. This is also what enables Fauna's built in Login function, which returns a new user Token. Your current application provides all users with permissions to read every user, including every user's password, and that is very, very bad.
Your errors
I see that you are trying to access the password field by doing result.password. Notice that when you created the document, password is under the data field.
if (result.data.password === password) {
alert("Login successful!");
} else {
alert("Incorrect email or password.");
}
A better way
You should follow along with the User Authentication Tutorial.
It is my recommendation that you turn signup and login into UDFs and use a public key that has two permissions (and only two permissions):
call Function("signup")
call Function("login")
Then your application can use the public key to access these functions. The login function then gives you a separate Token, which you use to make a new Fauna Client. That Token should have whatever privileges a user should have (but no more).
Fauna Community Resources
Forums: https://forums.fauna.com/
Discord: https://discord.gg/2qXynEjn

why page reload when posting or updating and item using fake rest api with json server

I'm using Json-Server for mocking API requests,
when fetching the post/ update the page reloads in each time which i do not know why, i searched for it and cant find any solution for that,
NB: i am following a javascript Tuturial and it didnt refresh from his side but it did in my side despite the codes were the same
class EasyHTTP {
async post(url,data){
const response = await fetch(url,{
method: 'POST',
headers:{'content-type':'application/json'},
body: JSON.stringify(data)
});
const resData = await response.json();
if(resData){
return resData;
}else{
await Promise.reject(new Error('ERROR: Dont Know'));
}
}
}
const http = new EasyHTTP();
// Submit POST
document.querySelector('.post-submit').addEventListener('click',submitPost);
function submitPost(e){
e.preventDefault();
//e.stopPropagation();
const title = document.querySelector('#title').value;
const body = document.querySelector('#body').value;
const data = {
title,
body
};
http.post('http://localhost:3000/posts',data)
.then(res => {
console.log(res);
})
.catch(err => console.log(err));
}
<input
type="text"
id="title"
class="form-control"
placeholder="Post Title"
/>
<textarea
id="body"
class="form-control"
placeholder="Post Body"
></textarea>
<button class="post-submit">Post It</button>
h post and i do not know where the problems comes from,
i found the solution, as I'm using VS code I disabled live-server extension and it worked perfectly fine now with no refreshing.

App.post returning empty set of curly braces

I'm building an express.js application that just takes data from A mysql database and displays on the screen and I'm trying too implement an insert functionality so I can add too the database via browser, when I post the results too one of the route points I am returned empty braces and do not know why,any help at all would be appreciated.
Index.js below this is addCountries.ejs
//brings you too add Country
app.get("/addCountries", (req, res) => {
res.render("addCountries")
console.log("hello")
})
//inserts data from add countries
app.post("/addCountries", (req, res) => {
sqlDAO.addCountry()
.then((data) => {
res.render("addCountries", {
addCountries: data
})
console.log(req.body.co_name)
console.log("hello")
})
.catch((error) => {
res.send(error)
console.log("hello")
})
})
<h1>Add Country</h1>
<br>
<br>
<form action="/addCountries" method="POST">
<label for="cCode">Country Code:</label>
<input type="text" id="cCode" name="co_code"><br><br>
<label for="cName">Country Name:</label>
<input type="text" id="cName" name="co_name"><br><br>
<label for="CDetails">Country Details:</label>
<textarea type="text" id="CDetails" name="co_details"></textarea>
<input type="submit" value="Add">
</form>
SQLDAO.js
var pool
//creates pool based on database provided by project spec
mysql.createPool({
connectionLimit: 3,
host: 'localhost',
user: 'root',
password: 'password',
database: 'geography'
})
.then((result) => {
pool = result
})
.catch((error) => {
console.log(error)
})
var addCountry = function() {
// returns new promise
return new Promise((resolve, reject) => {
// function that adds too database
var myQuery = {
sql: "INSERT INTO country VALUES (?, ?, ?)",
values: [req.body.co_code, req.body.co_name, req.body.co_details]
}
pool.query(myQuery)
.then((data) => {
resolve(data)
console.log(data)
})
.catch(error => {
reject(error)
})
})
}
You will need to pass a reference to the request object to addCountry(). This is because the addCountry() function inside the SQLDAO.js file does not have access to the request object.
Right now, in addCountry() the req variable is undefined, so when the SQL statement is compiled there is no data to insert. If you look in the DB you'll likely see empty or no records being added.
By passing in the request object, it has data to place into the db and that the db can return.
Edit both files like this:
sqlDAO.addCountry(req)... then var addCountry = function(req) {...
There are two reasons this is necessary:
Inside your app.post() function both req and res are scoped locally to the function and are unavailable outside that function.
Even if they were pseudo-global, variables are only available within the module they are created within. So you must export that variable or, in this case, pass a reference to it to some other function within some other module.

NodeJS and Javascript and HTML

If I have some HTML code:
<div>
<input type="text" name="user" placeholder="User Name" />
<input type="password" name="password" placeholder="Password" />
<button type="button">Login</button>
</div>
and when I click on the login button, it goes to the /api/users/ function in my nodejs file. How do I pass the strings stored in the username and password in the HTML code? Using sqlite3.
app.get('/api/users/', function (req, res) {
let sql = 'SELECT * FROM users;';
db.all(sql, [], (err, rows) => {
var result = {};
result["users"] = [];
if (err) {
result["error"] = err.message;
}else {
rows.forEach((row) => {
result["users"].push(row);
});
}
res.json(result);
});
});
I want to execute some type of function, where if the username and password does not exist, than add it to the table "users" and redirect to another HTML file.
You should use a html form. See here. You're HTML is just sending an empty get request to your API, a form will send the data as well.

Forgot Password Form using AWS Cognito

I am implementing a logic of forgot password using AWS Cognito. I am so far successful in changing the password using Prompts as given in the documentation. Here is the code
var username = document.getElementById('reset-pass').value;
var data = {
UserPoolId: _config.cognito.userPoolId,
ClientId: _config.cognito.clientId
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(data);
// setup cognitoUser first
var cognitoUser = new AmazonCognitoIdentity.CognitoUser({
Username: username,
Pool: userPool
});
cognitoUser.forgotPassword({
onSuccess: function (result) {
console.log('call result: ' + result);
},
onFailure: function(err) {
alert(err);
},
inputVerificationCode() {
var verificationCode = prompt('Please input verification code ' ,'');
var newPassword = prompt('Enter new password ' ,'');
cognitoUser.confirmPassword(verificationCode, newPassword, this);
}
});
My question is instead of using prompts, how can I confirm the user on next page. Example On the first page a user enter the email and mail is sent using the forgotPassword(). Now user is redirected to a new page. There i wanted to enter the code as well as the new password and call the cognitoUser.confirmPassword method.
What i tried is to create a delay interval and after entering the details it would trigger clear interval on button press.
function resetPassword() {
var username = document.getElementById('reset-pass').value;
var data = {
UserPoolId: _config.cognito.userPoolId,
ClientId: _config.cognito.clientId
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(data);
// setup cognitoUser first
var cognitoUser = new AmazonCognitoIdentity.CognitoUser({
Username: username,
Pool: userPool
});
// call forgotPassword on cognitoUser
cognitoUser.forgotPassword({
onSuccess: function (result) {
alert("Mail Sent")
},
onFailure: function (err) {
console.log(err)
},
inputVerificationCode()
{
window.myVar = setInterval(function(){
console.log('check');
}, 10000);
var verificationCode = document.getElementById('code').value;
var newPassword = document.getElementById('fpass').value;
cognitoUser.confirmPassword(verificationCode, newPassword, this);
}
});
}
The HTML Part Of the code-
<div class="change">
<form>
<label>Enter Email ID</label>
<input type="email" id="reset-pass" required />
<br />
<div class="">Next</div>
</form>
</div>
div class="change-confirm">
<form>
<label>Enter Code</label>
<input type="number" id="code" required />
<br />
<label>Enter New Password</label>
<input type="password" id="fpass" required />
<br />
<div class=""> Reset</div>
</form>
</div>
But the above code never executed. Instead it stops execution after some time.
So my question is is there any way to delay the function call of cognitoUser.confirmPassword method? I do not want to use prompts instead get the email and code in a text field after mail is sent.
A little late to the party, but it can help someone else.
You can pass the congitoUser you have created to the state, and then use cognitoUser.confirmPassword(...) by retrieving the cognitoUser object from the state.
You should consider using the aws-amplify-react which provides a withAuthenticator higher-order component that provides a login flow with forgot password, mfa, etc. And it's maintained by a team of devs who work for AWS.
https://aws-amplify.github.io/docs/js/react#add-auth

Categories

Resources