Whenever I try to add the user data, the wrong uid is being applied to the user data, it is applying the uid from the previous account created even after i have deleted the account from the database.
I read that i must create a child node to add the remaining user credentials which is what I am trying to do. But the current uid from the recieved promise is not being sent to the user database. please help.
second image
import React, { useState } from 'react'
import {v4 as uuid} from 'uuid'
import {db} from '../Features/util/firebase'
import {set,ref} from 'firebase/database'
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
function Register() {
const [fname, setFname]=useState('');
const [lname, setLname]=useState('');
const [phone, setPhone]=useState('');
const [email, setEmail]=useState('');
const [address, setAddress]=useState('');
const [username, setUsername]=useState('');
const [password, setPassword]=useState('');
const [uid, setUid]= useState('');
const createUser=(e)=>{
e.preventDefault();
const auth = getAuth();
createUserWithEmailAndPassword(auth,email,password)
.then((userCredential)=>{
console.log("signed in")
const user = userCredential.user;
console.log(user.uid);
setUid(userCredential.user.uid)
})
.then(()=>
set(ref(db,'users/') , {
fname:fname,
lname:lname,
phone:phone,
email:email,
address:address,
username:username,
userId:uid,
}))
.catch((error)=>{
const errorCode = error.code;
const errorMessage = error.message;
clearFields();
});
function clearFields (){
setAddress('');
setEmail('');
setFname('');
setLname('');
setPassword('');
setPhone('');
setUid('');
setUsername('');
}
}
return (
<div>
<form onSubmit={createUser}>
<label >First Name: </label>
<input type='text' value={fname} onChange={(e) => setFname(e.target.value)} required/><br/>
<label >Last Name: </label>
<input type='text' value={lname} onChange={(e) => setLname(e.target.value)} required ></input><br></br>
<label > Phone No.: </label>
<input type='tel' value={phone} onChange={(e) => setPhone(e.target.value)} required></input><br></br>
<label >e-Mail: </label>
<input type='email' value={email} onChange={(e) => setEmail(e.target.value)} required></input><br></br>
<label >Address: </label>
<input type='text' value={address} onChange={(e) => setAddress(e.target.value)} required></input><br></br>
<label >Username: </label>
<input type='text' value={username} onChange={(e) => setUsername(e.target.value)} required></input><br/>
<label >Password: </label>
<input type='password' value={password} onChange={(e) => setPassword(e.target.value)} required></input>
<input type='submit'></input>
</form>
</div>
)
}
export default Register
I was able to solve the problem with a different approach:
userId:auth.currentUser.uid,
Related
I have 4 input fields.
username,password,email,mobile.
if we type # in username field, the email field should disappear and if we type any digit in username then mobile field should disappear.
Help me with this.
I have created very basic code but not sure how to achive this.
import { useState } from "react";
export default function App() {
const [name, setname] = useState("");
const [password, setPassword] = useState("");
const [show, setShow] = useState();
if (name.includes("#")) {
setShow( ) //stuck here
}
return (
<>
<input
type="text"
placeholder="username"
value={name}
onChange={(e) => setname(e.target.value)}
/>
<input
type="password"
placeholder="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<input type="email" placeholder="email" id="email" />
<input type="number" placeholder="number" />
</>
);
}
Try below code
import { useState } from "react";
export default function App() {
const [name, setname] = useState("");
const [password, setPassword] = useState("");
//****************************************
const [show, setShow] = useState(false);
//****************************************
if (name.includes("#")) {
//****************************************
setShow(true) //stuck here
//****************************************
}
return (
<>
<input
type="text"
placeholder="username"
value={name}
onChange={(e) => setname(e.target.value)}
/>
<input
type="password"
placeholder="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
//****************************************
{ show?
<input type="email" placeholder="email" id="email" />:''}
//****************************************
<input type="number" placeholder="number" />
</>
);
}
we can use with && operator if our show is false then it hide on screen
import { useState } from "react";
export default function App() {
const [name, setname] = useState("");
const [password, setPassword] = useState("");
const [show, setShow] = useState(true);
if (name.includes("#")) {
setShow(false) //stuck here
}
return (
<>
<input
type="text"
placeholder="username"
value={name}
onChange={(e) => setname(e.target.value)}
/>
<input
type="password"
placeholder="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
{show && <input type="email" placeholder="email" id="email" />}
<input type="number" placeholder="number" />
</>
);
}
I'll give example with the email - you can apply same approach for the phone.
Some notes: you do not need a separate state whether to show email filed, it is derived from the name state.
Advice: You should not change state during the function render. You can do that on a user interaction (onClick, onChange etc) or useEffect hook if data fetch or another side effect.
The solution is simple
import { useState } from "react";
export default function App() {
const [name, setname] = useState("");
const [password, setPassword] = useState("");
const [show, setShow] = useState();
const showEmailField = name.includes("#"); //derived computed value base on the name state
return (
<>
<input
type="text"
placeholder="username"
value={name}
onChange={(e) => setname(e.target.value)}
/>
<input
type="password"
placeholder="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
{ showEmailField && <input type="email" placeholder="email" id="email" /> }
<input type="number" placeholder="number" />
</>
);
}
you can try using the useEffect hook.
try something like this .
in this way you can keep track of everytime name changes
useEffect(() => {
if (name.includes("#")) {
setShow();
}
}, [name]);
and then
show && (
<input
type="text"
placeholder="username"
value={name}
onChange={(e) => setname(e.target.value)}
/>
)
I am having an issue where my change function makes my checkboxes go from either true/false to just be 'on'. All the fields in my form use onInputChange and they all work accept for the checkboxes. So if I type in the text fields it updates properly and saves to my database with no issue but if I click a checkbox no matter the value that it started as it will change to 'on' and gives a cannot convert varchar to int error. I am looking for a new function to update the checkboxes properly and keep the onInputChange one for the text fields.
I did create one like below and it seems to change from true to false properly but 100% clears the rest of the data already in the form.
const onCheckboxChange = e => {
setUser({
active = !active });
console.log(user)
};
import React, { useState, useEffect } from "react";
import axios from "axios";
import { useParams, Link } from "react-router-dom";
const UpdateUser = () => {
const { collectorID } = useParams();
const [user, setUser] = useState({});
const {collectorOptionsID, programBucketID,financeCompanyID, active, firstName, middleInitial, lastName, collectorCode, aging1to15, aging31to45, aging31to60, agingOver60, programBucketA, programBucketB, programBucketC, programBucketSU, financeCompany, debtType } = user;
const onInputChange = e => {
setUser({
...user, [e.target.name]: e.target.value });
console.log(user)
};
useEffect(() => {
loadUser();
}, []);// eslint-disable-line react-hooks/exhaustive-deps
const loadUser = async () => {
const result = await axios.get(`https://support.pawneeleasing.com/PublishedCollectorAPI/api/Collector/${collectorID}`);
setUser(result.data);
console.log(result.data);
};
const onSubmit = async e => {
e.preventDefault();
console.log(active);
await axios.put(process.env.NODE_ENV === 'development' ? `${process.env.REACT_APP_DEV_UPDATE}${collectorID}` : `${process.env.REACT_APP_PRO_UPDATE}${collectorID}`, {
// await axios.put(`https://support.pawneeleasing.com/PublishedCollectorAPI/api/Collector/${collectorID}`, {
collectorID: collectorID,
collectorOptionsID: collectorOptionsID,
programBucketID: programBucketID,
financeCompanyID: financeCompanyID,
active: active,
firstName: firstName,
middleInitial: middleInitial,
lastName: lastName,
collectorCode: collectorCode,
debtType: debtType,
aging1to15: aging1to15,
aging31to45: aging31to45,
aging31to60:aging31to60,
agingOver60: agingOver60,
programBucketA: programBucketA,
programBucketB: programBucketB,
programBucketC: programBucketC,
programBucketSU: programBucketSU,
financeCompany: financeCompany,
});
};
return (
<div className="newUser">
<h1>Update Collector</h1>
<form className="newUserForm" >
<div className="newUserItem">
{/*active or inactive User*/}
<label>active</label>
<div className="newUserCheckboxContainer">
<input
type='checkbox'
name="active"
defaultChecked={active}
onClick={e => onInputChange(e)}
/>
</div>
{/*Collector First Name*/}
<label>First Name</label>
<input
type="text"
name="firstName"
placeholder="First Name"
defaultValue={firstName}
onChange={e => onInputChange(e)}
/>
{/*Collector Middle Initial*/}
<label>Middle Initial</label>
<input
type="text"
name="middleInitial"
placeholder="Middle Initial"
defaultValue={middleInitial}
onChange={e => onInputChange(e)}
/>
{/*Collector Last Name*/}
<label>Last Name</label>
<input
type="text"
name="lastName"
placeholder="Last Name"
defaultValue={lastName}
onChange={e => onInputChange(e)}
/>
{/*Collector Code First Initial Middle Initial Last Initial*/}
<label>Collector Code</label>
<input
type="text"
name="collectorCode"
placeholder="Collector Code"
defaultValue={collectorCode}
onChange={e => onInputChange(e)}
/>
{/*Aging Bucket selection section */}
<label>Aging Bucket</label>
<div className='newUserCheckboxContainer'>
<label className='newUserCheckboxLabel'>1-15<br/>
<input
type='checkbox'
className='AgingBucketCheckbox'
defaultValue={aging1to15}
defaultChecked={aging1to15}
onChange={e => onInputChange(e)}
/></label>
<label className='newUserCheckboxLabel'>31-45<br/>
<input
type='checkbox'
className='AgingBucketCheckbox'
defaultValue={aging31to45}
defaultChecked={aging31to45}
onChange={e => onInputChange(e)}
/></label>
<label className='newUserCheckboxLabel'>31-60<br/>
<input
type='checkbox'
className='AgingBucketCheckboxsm'
defaultValue={aging31to60}
defaultChecked={aging31to60}
onChange={e => onInputChange(e)}
/></label>
<label className='newUserCheckboxLabel'>Over 60<br/>
<input
type='checkbox'
className='AgingBucketCheckboxlg'
defaultValue={agingOver60}
defaultChecked={agingOver60}
onChange={e => onInputChange(e)}
/></label>
</div>
{/*Progam code selection section*/}
<label>Program Bucket</label>
<div className='newUserCheckboxContainer'>
<label className='newUserCheckboxLabel'>A<br/>
<input
type='checkbox'
className='programBucketChecbox'
defaultValue={programBucketA}
defaultChecked={programBucketA}
onChange={e => onInputChange(e)}
/></label>
<label className='newUserCheckboxLabel'>B<br/>
<input
type='checkbox'
className='programBucketChecbox'
defaultValue={programBucketB}
defaultChecked={programBucketB}
onChange={e => onInputChange(e)}
/></label>
<label className='newUserCheckboxLabel'>C<br/>
<input
type='checkbox'
className='programBucketChecbox'
defaultValue={programBucketC}
defaultChecked={programBucketC}
onChange={e => onInputChange(e)}
/></label>
<label className='newUserCheckboxLabel'>SU<br/>
<input
type='checkbox'
className='programBucketChecbox'
defaultValue={programBucketSU}
defaultChecked={programBucketSU}
onChange={e => onInputChange(e)}
/></label>
</div>
{/*Finance Company selection section*/}
<label>Finance Company</label>
<div className='newUserCheckboxContainer'>
<input
type="text"
name="financeCompany"
placeholder="financeCompany"
defaultValue={financeCompany}
onChange={e => onInputChange(e)}
/>
</div>
<label>Debt Type</label>
<div className='newUserCheckboxContainer'>
<input
type="text"
name="debtType"
placeholder="debtType"
defaultValue={debtType}
onChange={e => onInputChange(e)}
/>
</div>
<button type='submit' onClick={(event)=>onSubmit(event)} className="userListAddButton">Update Collector</button>
<Link className="userListGoBackButton" to='/users'>Go Back</Link>
</div>
</form>
</div>
);
}
export default UpdateUser;
You need to copy the rest of user properties by rest operator
const onCheckboxChange = e => {
setUser(prev => ({
...prev,
active: !prev.active
}))
};
I'm trying to register a user with firebase but I have an error in the console that I can't solve.
First of all I tried to display an error message in case the password is less than 6 characters, it displays an error at the console level and does not display the error message at the user page level.
Secondly when I register with correct identifiers it adds the user in the firebase but there is still an error
import React, { useState, useContext} from 'react'
import {FirebaseContext} from '../Firebase'
const SignUp = () => {
const firebase = useContext(FirebaseContext);
const data = {
pseudo: '',
email: '',
password: '',
confirmPassword: ''
}
const [loginData, setLoginData] = useState(data);
const [error, setError] = useState('')
const handleChange = e => {
setLoginData({...loginData, [e.target.id]: e.target.value})
}
const handleSubmit = e => {
e.preventDefault();
const {email, password} = loginData;
firebase.signUpUser(email, password)
.then(user =>{
setLoginData({...data})
})
.catch(error => {
setError(error);
setLoginData({...data})
})
}
const {pseudo, email, password, confirmPassword} = loginData;
const btn = pseudo === '' || email === '' || password === '' || password !== confirmPassword ? <button disabled>Inscription</button> : <button>Inscription</button>
const errorMsg = error !== '' && <span> {error.message} </span>
return (
<div className='signUpLoginBox'>
<div className="slContainer">
<div className='formBoxLeftSignup'>
</div>
<div className='formBoxRight'>
<div className='formContent'>
{errorMsg}
<h2>Inscription</h2>
<form onSubmit={handleSubmit}>
<div className='inputBox'>
<input onChange={handleChange} value={pseudo} type="text" id='pseudo' required/>
<label htmlFor="pseudo">Pseudo</label>
</div>
<div className='inputBox'>
<input onChange={handleChange} value={email} type="email" id='email' required/>
<label htmlFor="email">Email</label>
</div>
<div className='inputBox'>
<input onChange={handleChange} value={password} type="password" id='password' required/>
<label htmlFor="password">Mot de passe</label>
</div>
<div className='inputBox'>
<input onChange={handleChange} value={confirmPassword} type="password" id='confirmPassword' required/>
<label htmlFor="confirmPassword">Confirmez le mot de passe</label>
</div>
{btn}
</form>
</div>
</div>
</div>
</div>
)
}
export default SignUp
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
error when the password does not reach the 6th character and the error message is not displayed on the page
error when registration is successful
I am having issues with the axios post request. When I click on the Button, nothing happens. What is supposed to happen is that the data that I enter into the input fields is submitted to the API. However, no redirect or anything happens when I click the Button. I am not sure whether the onClick function in the Button is never being triggered or whether the issue lies with the call of axios and then the useNavigate function. I have tried several different ways of using these function but none worked. It might be a syntactic issue as I am a beginner with react. Any help would be appreciated!
Full Code:
import axios from 'axios';
import React, { useState } from 'react';
import { Container, Button } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
const AddContact = () => {
const [first_name, setFirstName] = useState("")
const [last_name, setLastName] = useState("")
const [mobile_number, setMobileNumber] = useState("")
const [home_number, setHomeNumber] = useState("")
const [work_number, setWorkNumber] = useState("")
const [email_address, setEmailAddress] = useState("")
const history = useNavigate();
const AddContactInfo = async () => {
let formField = new FormData();
formField.append('first_name', first_name)
formField.append('last_name', last_name)
formField.append('mobile_number', mobile_number)
formField.append('home_number', home_number)
formField.append('work_number', work_number)
formField.append('email_address', email_address)
await axios.post('http://localhost:8000/api/', {
data: formField
}).then(function (response) {
console.log(response.data);
history('/', { replace: true });
})
}
return (
<div>
<h1>Add contact</h1>
<Container>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your First Name"
first_name="first_name"
value={first_name}
onChange={(e) => setFirstName(e.target.value)} />
</div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Last Name"
last_name="last_name"
value={last_name}
onChange={(e) => setLastName(e.target.value)} />
</div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Mobile Number"
mobile_number="mobile_number"
value={mobile_number}
onChange={(e) => setMobileNumber(e.target.value)} /></div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Home Number"
home_number="home_number"
value={home_number}
onChange={(e) => setHomeNumber(e.target.value)} /></div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Work Number"
work_number="work_number"
value={work_number}
onChange={(e) => setWorkNumber(e.target.value)} /></div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Email Address"
email_address="email_address"
value={email_address}
onChange={(e) => setEmailAddress(e.target.value)} /></div>
<Button onClick={() => { AddContactInfo(); }}>
Add Contact
</Button>
</Container>
</div >
);
};
export default AddContact;
First rename AddContactInfo to addContactInfo and then:
<Button onClick={addContactInfo}>
Add Contact
</Button>
You should correct the method addContactInfo as below:
const AddContactInfo = () => {
let formField = new FormData();
formField.append('first_name', first_name)
formField.append('last_name', last_name)
formField.append('mobile_number', mobile_number)
formField.append('home_number', home_number)
formField.append('work_number', work_number)
formField.append('email_address', email_address)
axios.post('http://localhost:8000/api/', {
data: formField
}).then(function (response) {
console.log(response.data);
history('/', { replace: true });
})
}
Try This:
<Button onClick={AddContactInfo}>
Add Contact
</Button>
import axios from 'axios';
const url = 'http://localhost:8000/api/';
axios.post(url , formField)
.then(response => {
console.log(response.data);
history('/', { replace: true });
})
.catch(({response}) => {
console.log(response);
});
Try calling the function this way :)
<Button onClick={AddContactInfo}>
Add Contact
</Button>
I am trying to create a register and login page where the registered user's details are setn to the database and then from there they are used to verify login.
The sign up button is supposed to send data to the database, hence registering a user. After that, in the login form the data os authenticated and the user logs in.
I haven't gotten to the login part, still stuck on the sign up part.
I don't get any errors displayed, it is just that my data is not being fed to the database.
index.js for nodejs:
//var { app } = require("cli");
const express = require("express");
const mysql = require("mysql");
const cors = require("cors");
app = express();
app.use(express.json());
app.use(cors());
const db = mysql.createConnection({
user: "root",
host: "localhost",
password: "",
database: "crm database",
});
app.post("/register", (req, res) => {
const CompanyCode = req.body.CompanyCode;
const UserID = req.body.UserID;
const UserFullName = req.body.UserFullName;
const UserDetail = req.body.UserDetail;
const LoginID = req.body.LoginID;
const Password = req.body.Password;
const ConfirmPassword = req.body.ConfirmPassword;
const UserPin = req.body.UserPin;
const UserEmailID = req.body.UserEmailID;
db.query(
"INSERT INTO usermst (CmpnyCode,UserID,UserFullName,UserDetail,LoginID,Password,UserPin,UserEmailID) VALUES (?,?,?,?,?,?,?,?)",
[
CompanyCode,
UserID,
UserFullName,
UserDetail,
LoginID,
Password,
UserPin,
UserEmailID,
],
(err, result) => {
console.log(err);
}
);
});
app.listen(8000, () => {
console.log("Server running on port 8000");
});
app.js for react js:
import "bootstrap/dist/css/bootstrap.min.css";
import React, { useState } from "react";
//import { BrowserRouter, Switch, Route } from "react-router-dom";
import "./App.css";
import axios from "axios";
function App() {
const [CompanyCodeReg, setCompanyCodeReg] = useState("");
const [UserIDReg, setUserIDReg] = useState("");
const [UserFullNameReg, setUserFullNameReg] = useState("");
const [UserDetailReg, setUserDetailReg] = useState("");
const [LoginIDReg, setLoginIDReg] = useState("");
const [PasswordReg, setPasswordReg] = useState("");
const [ConfirmPasswordReg, setConfirmPasswordReg] = useState("");
const [UserPinReg, setUserPinReg] = useState("");
const [UserEmailIDReg, setUserEmailIDReg] = useState("");
const register = () => {
axios
.post("http://localhost8000/register", {
CompanyCode: CompanyCodeReg,
UserID: UserIDReg,
UserFullName: UserFullNameReg,
UserDetail: UserDetailReg,
LoginID: LoginIDReg,
Password: PasswordReg,
ConfirmPassword: ConfirmPasswordReg,
UserPin: UserPinReg,
UserEmailID: UserEmailIDReg,
})
.then((response) => {
console.log(response);
});
};
return (
<div className="App">
<nav className="navbar navbar-expand navbar-light fixed-top">
<div className="container">Home</div>
</nav>
<div className="auth-wrapper">
<div className="auth-inner">
<form>
<h3>Sign Up</h3>
<div className="form-group">
<label>Company Code</label>
<input
type="text"
className="form-control"
placeholder="CompanyCode"
onChange={(e) => {
setCompanyCodeReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>User ID</label>
<input
type="text"
className="form-control"
placeholder="UserID"
onChange={(e) => {
setUserIDReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>User Full Name</label>
<input
type="text"
className="form-control"
placeholder="UserFullName"
onChange={(e) => {
setUserFullNameReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>User Detail</label>
<input
type="text"
className="form-control"
placeholder="UserDetail"
onChange={(e) => {
setUserDetailReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>Login ID</label>
<input
type="text"
className="form-control"
placeholder="LoginID"
onChange={(e) => {
setLoginIDReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>Password</label>
<input
type="password"
className="form-control"
placeholder="Password"
onChange={(e) => {
setPasswordReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>Confirm Password</label>
<input
type="password"
className="form-control"
placeholder=" ConfirmPassword"
onChange={(e) => {
setConfirmPasswordReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>User Pin</label>
<input
type="Text"
className="form-control"
placeholder="UserPin"
onChange={(e) => {
setUserPinReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>UserEmailID</label>
<input
type="email"
className="form-control"
placeholder="UserEmailID"
onChange={(e) => {
setUserEmailIDReg(e.target.value);
}}
/>
</div>
<button className="btn btn-primary btn-block" onClick={register}>
Sign Up
</button>
</form>
</div>
<div className="auth-inner">
<form>
<h3>Log In</h3>
<div className="form-group">
<label>Login ID</label>
<input
type="text"
className="form-control"
placeholder="First Name"
/>
</div>
<div className="form-group">
<label>Password</label>
<input
type="password"
className="form-control"
placeholder="Password"
/>
</div>
<button className="btn btn-primary btn-block">Login</button>
</form>
</div>
</div>
</div>
);
}
export default App;
You have to send the response back to the client, you can do so with the res object like
res.json({ result });
app.post("/register", (req, res) => {
const CompanyCode = req.body.CompanyCode;
const UserID = req.body.UserID;
const UserFullName = req.body.UserFullName;
const UserDetail = req.body.UserDetail;
const LoginID = req.body.LoginID;
const Password = req.body.Password;
const ConfirmPassword = req.body.ConfirmPassword;
const UserPin = req.body.UserPin;
const UserEmailID = req.body.UserEmailID;
db.query(
"INSERT INTO usermst (CmpnyCode,UserID,UserFullName,UserDetail,LoginID,Password,UserPin,UserEmailID) VALUES (?,?,?,?,?,?,?,?)",
[
CompanyCode,
UserID,
UserFullName,
UserDetail,
LoginID,
Password,
UserPin,
UserEmailID,
],
(err, result) => {
console.log(err);
// You have missed this line
res.json({ result });
}
);
});
I just realized that I was violating my own database foreign key constraints.
I added the following line:
db.connect((err) => {
if (err) {
console.log(err);
}
console.log("Connected to MySQL Server!");
});```
after creating the database connection and it displayed to me what was going wrong.