Nodejs + mySQL data does not get sent to my database - javascript

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.

Related

Error message, Warning Cannot update a component (`BrowserRouter`) while rendering a different component

So ive got this error, im guessing its something with my use navigate, but im not shure.
Ive have read alot and searched for the solution but i cant find any way to solve the issue.
The issue only comes after ive have logged in. At the moment i dont have any access token on the backend.
react_devtools_backend.js:4026 Warning: Cannot update a component (BrowserRouter) while rendering a different component (Login). To locate the bad setState() call inside Login, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
at Login (http://localhost:3000/static/js/bundle.js:3571:82)
at div
at LoginPage
at Routes (http://localhost:3000/static/js/bundle.js:129199:5)
at Router (http://localhost:3000/static/js/bundle.js:129132:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:127941:5)
import React from 'react';
import { useRef, useState, useEffect } from 'react'
// import { useContext } from 'react'
//import AuthContext from './context/AuthProvider';
import axios from './api/axios';
const LOGIN_URL = '/login';
const REG_URL = '/newUser'
export default function Login() {
const [authMode, setAuthMode] = useState("signin");
const changeAuthMode = () => {
setAuthMode(authMode === "signin" ? "signup" : "signin");
}
//const { setAuth } = useContext(AuthContext);
const userRef = useRef();
const errRef = useRef();
const [userName, setUserName] = useState("");
const [password, setPassword] = useState("");
const [errMsg, setErrMsg] = useState('');
const [success, setSuccess] = useState(false);
const [register, setRegister] = useState(false);
useEffect(() => {
userRef.current.focus();
}, [])
useEffect(() => {
setErrMsg('');
}, [userName, password])
const handleRegister = (e) => {
// prevent the form from refreshing the whole page
e.preventDefault();
// set configurations
const RegConfiguration = {
method: "post",
url: REG_URL,
data: {
userName,
password,
},
};
// make the API call
axios(RegConfiguration)
.then((result) => {
setRegister(true);
})
.catch((error) => {
error = new Error();
});
};
///HANDLE Login part.
const handleLogin = async (e) => {
e.preventDefault();
try {
await axios.post(LOGIN_URL,
JSON.stringify({ userName, password }),
{
headers: { 'Content-type': 'application/json' },
withCredentials: false,
}
);
//const token = response?.data?.token;
//setAuth({ userName, password, token })
//console.log(JSON.stringify(respone));
setUserName('');
setPassword('');
setSuccess(true);
} catch (err) {
if (!err?.response) {
setErrMsg('No Server Response');
} else if (err.response?.status === 400) {
setErrMsg('Missing Username or Password');
} else if (err.response?.status === 401) {
setErrMsg('Unauthorized');
}
else {
setErrMsg('Login Failed');
}
errRef.current.focus();
}
}
const Navigate = useNavigate();
if (authMode === "signin") {
return (
<> {success ? (
Navigate('/authlog')
) : (
<div className="Auth-form-container">
<form className="Auth-form" >
<div className="Auth-form-content">
<h3 className="Auth-form-title">Sign In</h3>
<div className="text-center">
Not registered yet?{" "}
<span className="link-primary" onClick={changeAuthMode} >
Sign Up
</span>
</div>
<div className="form-group mt-3">
<label>Username </label>
<input
className="form-control mt-1"
id='userName'
ref={userRef}
name="userName"
value={userName}
placeholder="username"
onChange={(e) => setUserName(e.target.value)}
/>
</div>
<div className="form-group mt-3">
<label>Password</label>
<input
className="form-control mt-1"
name="password"
type="password"
id='password'
value={password}
placeholder="password"
required
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="d-grid gap-2 mt-3">
<button
type="submit"
className="btn btn-primary"
onClick={(e) => handleLogin(e)}
>
Logga in
</button>
<p ref={errRef} className={errMsg ? "errmsg" : "offscreen"} aria-live="assertive">{errMsg}</p>
</div>
</div>
</form>
</div>
)}</>
)
}
// "Register page"
return (
<div className="Auth-form-container">
<form className="Auth-form" onSubmit={(e) => handleRegister(e)}>
<div className="Auth-form-content">
<h3 className="Auth-form-title">Sign In</h3>
<div className="text-center">
Already registered?{" "}
<span className="link-primary" onClick={changeAuthMode}>
Go to Sign In
</span>
</div>
<div className="form-group mt-3">
<label>Register Your Username here</label>
<input
className="form-control mt-1"
name="userName"
value={userName}
placeholder="ure username here:"
onChange={(event) => setUserName(event.target.value)}
/>
</div>
<div className="form-group mt-3">
<label>Register Youre password</label>
<input
className="form-control mt-1"
type="password"
name="password"
value={password}
placeholder="ure password here"
onChange={(event) => setPassword(event.target.value)}
/>
</div>
<div className="d-grid gap-2 mt-3">
<button type="submit" className="btn btn-primary" onClick={handleRegister}>
Registera
</button>
{/* display success message */}
{register ? (
<p className="text-success">You Are Now Registered Successfully</p>
) : (
<p className="text-danger">Please register your account here</p>
)}
</div>
</div>
</form>
</div>
);
}

Parsing error: 'return' outside of function

I've recently started maintaining JavaScript code and now i am facing trouble in the returning function in line 39. Can someone please help? I have checked the syntax and can't find anything wrong................................................................???????????????????????????????????????????????????????????????????????
import React, { useState, useEffect} from "react";
import axios from "axios";
import { renderMatches, useNavigate, useParams, } from "react-router-dom";
const Editorg = () => {
let navigate = useNavigate();
const {id} = useParams();
console.log(id);
const [user, setUser] = useState ({
name:"",
poname:"",
type:"",
ostatus:"",
});
const { name, poname, type, ostatus } = user;
const onInputChange = e => {
setUser({...user, [e.target.name]: e.target.value });
};
useEffect(() => {
loadUser();
}, []);
};
const onSubmit = async e => {
e.preventDefault();
await axios.put( 'http://localhost:3001/users/${id}' , user);
navigate.push("/");
};
const loadUser = async () =>{
const result = await axios.get('http://localhost:3001/users/${id}', user);
setUser(result.data);
};
return (
<div className="container">
<div className="w-75 mx-auto shadow p-5">
<h5 className="text-left mb-4"> Edit Organization </h5>
<form onSubmit={e => onSubmit(e)}>
<div className="form-group">
<label> Organization Name </label>
<input type="text" className="form-control" name="name" value={name}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<label> Parent Organization Name </label>
<input type="text" className="form-control" name="poname" value={poname}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<label> Type </label>
<input type="text" className="form-control" name="type" value={type}
onChange={e => onInputChange(e)}
/></div>
<div className="form-group">
<label> Organization Status </label>
<input type="text" className="form-control" name="ostatus" value={ostatus}
onChange={e => onInputChange(e)}
/></div>
<div className="container">
<div className="btn-6">
<button className="btn btn-danger float-right">Update</button>
</div>
</div>
</form>
</div>
</div>
);
}
Around line 26 you are closing the function too early.
useEffect(() => {
loadUser();
}, []);
}; // <- Move this to the very end
const onSubmit = async e => {
</div>
</div>
);
}; // <- Move to here
You mistakly add extra termination of curly bracket
useEffect(() => {
loadUser();
}, []);
}; // <--- remove this

(react & firebase ) Uncaught TypeError: Cannot read properties of undefined (reading 'then')

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 trying to add user information to firebase createuserwithemailandpassword

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,

How do I make a POST request using axios in react?

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>

Categories