Getting a specific user from MYSQL with axios Get - mysql

I'm at the very end of my project, I'm using react js frontend and express and mysql, I have everything working but the last step, I have a input field that is suppose to allow a user to enter a email or phone number and hit search, It's suppose to search the database and display that user's info, I have it when you hit search it displays all the data from the database, I need it to search and find the data the user is requesting, I can't find any documentation. here is my front end code.
import React, { useState, useEffect } from "react";
import "./Home.css";
import BattleAxe from "./battleaxes.png";
import { Link } from "react-router-dom";
import axios from "axios";
export default function Home() {
const [searchResults, setSearchResults] = useState([]);
const handleSubmit = (e) => {
e.preventDefault();
axios.get("http://localhost:3001/api/get").then((response) => {
setSearchResults(response.data);
});
};
return (
<div className="home-container">
<img src={BattleAxe} alt="" className="axe-image" />
<div>
<h2 className="heading"> Welcome to Battle Axes!</h2>
</div>
<div className="split">
<div className="newc">
<p className="info1">
<strong>First Timer?</strong>
</p>
<p className="info3">
Click the 'New Customer'
<br />
button to get started.
</p>
<Link to="/NewCustomer">
<button className="new-customer">New Customer</button>
</Link>
</div>
<div className="returnc">
<h3 className="info2">Returning Customer?</h3>
<p className="info4">
Enter your Email or Phone
<br />
below to find your acount.
</p>
<form onSubmit={handleSubmit}>
<input type="text" className="text-field" />
<button className="search-btn">Search</button>
</form>
</div>
</div>
<div className="search-results">
{searchResults.map((val) => {
return (
<p className="srlist">
{val.firstName} | {val.lastName}
<br />
<br />
{val.email}
<br />
<br />
{val.phone}
<Link to="/WaiverForm">
<button className="sel-btn">Select</button>
</Link>
</p>
);
})}
</div>
</div>
);
}
here is my backend.
const express = require("express");
const app = express();
const mysql = require("mysql");
const bodyParser = require("body-parser");
const cors = require("cors");
const { response } = require("express");
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "Killer12!",
database: "cloneDataBase",
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/api/get", (req, res) => {
const sqlGet = "SELECT * FROM customer_registration";
db.query(sqlGet, (error, result) => {
res.send(result);
});
});
app.post("/api/post", (req, res) => {
const { firstName, lastName, email, phone, nickName } = req.body;
const sqlInsert =
"INSERT INTO customer_registration (firstName, lastName, email, phone, nickName) VALUES (?,?,?,?,?)";
db.query(
sqlInsert,
[firstName, lastName, email, phone, nickName],
(error, result) => {
if (error) {
console.log(error);
res.send("False");
}
}
);
res.send("Customer created");
});
app.post("/api/waiver", (req, res) => {
const userSignature = req.body.userSignature;
const sqlInsert = "INSERT INTO waiver_signature (userSignature) VALUES (?)";
db.query(sqlInsert, userSignature, (err, result) => {
if (err) {
console.log(err);
}
});
res.send("Signature created");
});
app.listen(3001, () => {
console.log("running on port 3001");
});

You can create an endpoint where you are receving query params either email or phone number
app.get("/api/get", (req, res) => {
let email = req.query.email ?? '';
let phone = req.query.phone ?? '';
const sqlGet = "SELECT * FROM customer_registration WHERE email = ? OR phone = ?";
db.query(sqlGet, [email, phone], (error, result) => {
res.send(result);
});
});
In your frontend, you can send data in query params, You can plug in your email and phone like this below
axios.get("http://localhost:3001/api/get", { params: { email: email, phone: phone} })

Related

error adding data to mysql column and all column counted as NULL

Hello so i started the project using react, node js, and mysql.
My goal is to create a form in frontend and want to add the data in form to mysql database.
But after submiting there is a error'INSERT INTO employee (Name, Age, Position, Salary) VALUES (NULL,NULL,NULL,NULL)'.
The problem here is in all column it says "cannot be null". How do i solve this.
App.js
import React,{ useState, useEffect} from 'react';
import './App.css';
import Axios from 'axios';
function App() {
const [employeeName, setName] = useState("")
const [employeeAge, setAge] = useState("")
const [employeePosition, setPosition] = useState("")
const [employeeSalary, setSalary] = useState("")
const submitData = () => {
Axios.post('http://localhost:3001/api/insert', {
Name: employeeName,
Age: employeeAge,
position: employeePosition,
Salary: employeeSalary
}).then(()=>{
alert('Berhasil')
})
}
return (
<div className="App">
<p>CRUD Applicaiton</p>
<div className="formControl">
<label>Name</label>
<input type="text" onChange={(e)=> {
setName(e.target.value);
}} />
<label>Age</label>
<input type="number" onChange={(e)=> {
setAge(e.target.value);
}} />
<label>Position</label>
<input type="text" onChange={(e)=> {
setPosition(e.target.value);
}} />
<label>Salary</label>
<input type="number" onChange={(e)=> {
setSalary(e.target.value);
}} />
<button type="submit" value="Submit" onClick={submitData}>Add Data</button>
<button type="reset" value="Reset">Reset</button>
</div>
</div>
);
}
export default App;
index.js (backend)
const express = require('express');
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
const mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "",
database: "coba"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));
app.post("/api/insert", (req, res) => {
const Name = req.body.employeeName
const Age = req.body.employeeAge
const Position = req.body.employeePosition
const Salary = req.body.employeeSalary
const sqlInsert = "INSERT INTO employee (Name, Age, Position, Salary) VALUES (?,?,?,?)"
db.query(sqlInsert, [Name, Age, Position, Salary], (err, result)=>{
console.log(err)
});
})
app.listen(3001, ()=> {
console.log('running on port 3001')
});
You need to change your backend code.
Try once with the following code:
app.post("/api/insert", (req, res) => {
const Name = req.body.Name
const Age = req.body.Age
const Position = req.body.position
const Salary = req.body.Salary
const sqlInsert = "INSERT INTO employee (Name, Age, Position, Salary) VALUES (?,?,?,?)"
db.query(sqlInsert, [Name, Age, Position, Salary], (err, result)=>{
console.log(err)
});
})

React, Node Express, Mysql registration form stuck

I'm learning how to connect my front end to a database using middleware and trying to clone a waiver/registration form for a project my buddy gave me.
I can manually input data from the code editor to Mysql database but once I try to link it to the front end I get nothing, I'm completely stumped, can't really find any updated documentation on Node express syntax and mysql.
Here is my server and database code:
const express = require("express");
const app = express();
const mysql = require("mysql");
const bodyParser = require("body-parser");
const cors = require("cors");
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "cloneDataBase",
});
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/api/get", (req, res) => {
const sqlGet = "SELECT * FROM customer_registration";
db.query(sqlGet, (error, result) => {
res.send(result);
});
});
app.post("/api/post", (req, res) => {
const { firstName, lastName, email, phone, nickName } = req.body;
const sqlInsert =
"INSERT INTO customer_registration (firstName, lastName, email, phone, nickName) VALUES (?,?,?,?,?)";
db.query(
sqlInsert,
[firstName, lastName, email, phone, nickName],
(error, result) => {
if (error) {
console.log(error);
}
}
);
});
heres my registration form.
import React, { useState } from "react";
import "./NewCustomer.css";
import { Link, useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import axios from "axios";
const initialState = {
firstName: "",
lastName: "",
email: "",
phone: "",
nickName: "",
};
export default function NewCustomer() {
const [state, setState] = useState(initialState);
const { firstName, lastName, email, phone, nickName } = state;
const navigate = useNavigate();
const handleSubmit = (e) => {
e.preventDefalut();
if (!firstName || !lastName || !email || !phone || !nickName) {
toast.error("Please Provide value into each input field");
} else {
axios
.post("http://localhost:3001/api/post", {
firstName,
lastName,
email,
phone,
nickName,
})
.then(() => {
setState({
firstName: "",
lastName: "",
email: "",
phone: "",
nickName: "",
});
})
.catch((err) => toast.error(err.response.data));
setTimeout(() => navigate.push("/"), 500);
}
};
// const handleInputChange = (e) => {
// const { name, value } = e.target;
// setState({ ...state, [name]: value });
// };
return (
<div className="container">
<div className="new-customer-reg">
<Link to="/">
<button className="center-button-startover">Start Over</button>
</Link>
<div className="form-in">
<form onSubmit={handleSubmit} className="new-customer-form">
<label for="firstName">First Name*</label>
<input
type="text"
name="first_name"
required
// value={firstName}
// onChange={handleInputChange}
/>
<br />
<label for="lastName">Last Name*</label>
<input
type="text"
name="last_name"
required
// value={lastName}
// onChange={handleInputChange}
/>
<br />
<label for="email">Email*</label>
<input
type="email"
className="email"
required
// value={email}
// onChange={handleInputChange}
/>
<br />
<label for="phone">Phone*</label>
<input
type="tel"
className="phone"
required
// value={phone}
// onChange={handleInputChange}
/>
<br />
<label for="nickName">Nickname</label>
<input
type=" text"
className="nickname"
// value={nickName}
// onChange={handleInputChange}
/>
<div className="input-with-optional">
<span className="nick-helper">
(optional) This will be displayed instead of your first name.
</span>
<br />
</div>
<button onSubmit={handleSubmit} type="submit" className="regi">
Register
</button>
</form>
</div>
</div>
</div>
);
}enter code here
You forgot to send a response from your POST route handler. For example:
res.send('Customer created')
Additionally, in your frontend you have a typo (preventDefalut) which will make your code crash.

server crashed down when I was trying to login the data for testing validation

I was trying to input wrong data to see how the server getting data from the database and responding to the client if there is any incorrect like wrong username/password or username does not exist. It worked perfectly and responded for 1 to 2 times until the third time the crash happened:
Cannot set headers after they are sent to the client
ERR_CONNECTION_REFUSED``
Here is my server-side:
const express = require("express");
const router = express.Router();
const { Users } = require("../models");
const bcrypt = require('bcryptjs');
router.post("/", async (req, res) => {
const {username, password, phone, email} = req.body;
const user = await Users.findOne({ where: {username: username}});
if(user) {
res.json({ error: "User is unavailable"});
} else {
bcrypt.hash(password, 10).then((hash) => {
Users.create({
username: username,
password: hash,
phone: phone,
email: email,
});
res.json("SUCCESS");
});
};
});
router.post("/login", async (req, res) => {
const { username, password } = req.body;
const user = await Users.findOne({ where: { username: username } });
if (!user) res.json("User Doesn't exist");
bcrypt.compare(password, user.password).then((match) => {
if (!match) res.json("Wrong Username or Password");
res.json("YOU LOGGED IN");
});
});
module.exports = router;
and Here is my client side:
import {FontAwesomeIcon} from '#fortawesome/react-fontawesome';
import {faUser, faLock, faEye, faEyeSlash} from '#fortawesome/free-solid-svg-icons';
import { BiUser } from "react-icons/bi";
import {Link} from 'react-router-dom';
import { useState } from 'react';
import axios from 'axios';
function Register() {
const [username, setUsername] = useState("");
const [password, setPassword]= useState("");
const [type, setType] = useState("password");
const [icon, setIcon] = useState(faEye);
const handleShowHidePass = () => {
let currentType = type === "password" ? "text" : "password";
let currentIcon = icon === faEye ? faEyeSlash : faEye;
setType(currentType);
setIcon(currentIcon);
}
const login = e => {
e.preventDefault();
axios.post ("http://localhost:3001/auth/login", {
username: username,
password: password,
}).then((res) =>{
console.log(res.data);
});
};
return(
<div className="right">
<span className="title"><BiUser className="tilteIcon"/></span>
<form onSubmit={login} >
<div className="formInput">
<span className="icon"><FontAwesomeIcon icon={faUser}/></span>
<input
type="text"
className="username"
value={username}
placeholder="Username"
onChange={(e) => {
setUsername(e.target.value)
}}
/>
</div>
<div className="formInput">
<span className="icon"><FontAwesomeIcon icon={faLock}/></span>
<input
type={type}
className="password1"
value={password}
placeholder="Password"
onChange={(event) => {
setPassword(event.target.value)
}}
/>
<span className="show"><FontAwesomeIcon icon={icon} onClick={handleShowHidePass}/></span>
</div>
<div className="formInput">
<button type="submit">Sign Up</button>
</div>
<div className="login">
<Link to="/register" style={{textDecoration: 'none'}}>I already have an account!</Link>
</div>
</form>
</div>
);
}
export default Register;
use return with this line if (!user) return res.json("User Doesn't exist");
your code is executing further after sending the response

Axios post is giving me an error: Internal server Error

I am doing a post request with Axios and gives me this error:
xhr.js:178 POST http://localhost:3000/dependentes 500 (Internal Server
Error)
I have seen people asking about this but none of their solutions work for me!
I don't know if is something wrong in this component or I have something wrong with the server side.
import React, { Component } from "react";
import axios from "axios";
class LogIn extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeEmail = this.handleChangeEmail.bind(this);
this.handleChangePass = this.handleChangePass.bind(this);
}
handleChangeEmail = e => {
this.setState({ email: e.target.value });
//console.log(e.target.value);
};
handleChangePass = e => {
this.setState({ password: e.target.value });
//console.log(e.target.value);
};
handleSubmit = e => {
/*this.props.history.push('/');
console.log(this.props);*/
event.preventDefault();
let data = JSON.stringify({
email: this.state.email,
password: this.state.password
});
let url = "http://localhost:3000/dependentes";
const response = axios.post(url, data, {
headers: { "Content-Type": "application/json" }
});
};
render() {
return (
<div className="container">
<form onSubmit={this.handleSubmit} className="white">
<h5 className="grey-text text-darken-3">Log In</h5>
<div className="input-field">
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
onChange={this.handleChangeEmail}
value={this.state.email}
/>
</div>
<div className="input-field">
<label htmlFor="password">Password</label>
<input
type="password"
id="password"
onChange={this.handleChangePass}
/>
</div>
<div className="input-field">
<button className="btn orange lighten-1 z-depth-0">Log In</button>
</div>
</form>
</div>
);
}
}
export default LogIn;
According to your node.js code you are NOT using body-parser that's why getting email from req.body will throw you an error because req.body is undefined.
Also, If you don't return the request like res.send or res.json it will always time out from front end as the request is not closed.
So, to edit your code
//installed express, mysql, cors
const config = require('./database/config');
const express = require('express');
const cors = require('cors');
const port = 4000;
const app = express();
const mysql = require('mysql');
const bodyParser = require('body-parser'); // <=== this line
app.use(cors());
app.use(bodyParser.json()); //<=== This line
const SELECT_ALL_ADDICTS_QUERY = 'SELECT * FROM viciados';
const connection = mysql.createConnection(config.mysql);
connection.connect(err => {
if (err) {
return err;
}
});
app.get('/', (req, res) => {
res.send('Homepage. Go to /dependentes para ver os dependentes no sistema');
res.end();
});
app.get('/dependentes', (req, res) => {
connection.query(SELECT_ALL_ADDICTS_QUERY, (err, results) => {
if (err) {
res.send(err);
} else {
res.json({
data: results
});
}
});
});
app.post('/dependentes', (req, res) => {
console.log(req.body.email);
res.json({ email: req.body.email }); ///<== and this line
});
app.listen(port, err => {
return err
? console.log(`error founded: ${err}`)
: console.log(`server runnning on port: ${port}`);
});

Handling GET request with axios and express

I am really new to react. I created a simple form with bootstrap.
I created a MySQL database. I set up an express server on port 3001 and was able to post my form data to the database successfully.
Now I am trying to send an id through the form and get the details. Can someone please guide me through this. I looked over the internet but could not find a clear example yet.
Thanks in advance
My app.js:
import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";
import "./App.css";
import axios from "axios";
import { Form } from "react-bootstrap";
class App extends Component {
constructor(props) {
super(props);
this.state = {
id: "",
fName: "",
lName: "",
password: "",
email: "",
persons: [],
};
}
handleOnSubmit(event) {
event.preventDefault();
alert("Data Submitted Successfully");
//--------------------------------------------------------------------------------
//POST Request
// const user = {
// fName : this.state.fName,
// lName : this.state.lName,
// // email : this.state.email,
// // password : this.state.password,
// };
// axios.post(`http://localhost:3001`, { user })
// .then(res => {
// console.log(res);
// console.log(res.data);
// })
}
handleOnChange(event) {
let name = event.target.name;
let value = event.target.value;
this.setState({
[name]: value
});
}
//GET Request
handleOnSearch() {
axios.get(`http://localhost:3001`,{
params: {
id: this.state.id
}
})
.then(res => {
console.log(this.state.persons);
this.setState({ persons: res.data });
});
}
render() {
return (
<div>
<Form onSubmit={this.handleOnSubmit.bind(this)}>
<Form.Group controlId="firstName">
<Form.Label>First Name</Form.Label>
<Form.Control
type="text"
placeholder="Enter first name"
name="fName"
onChange={this.handleOnChange.bind(this)}
/>
</Form.Group>
<Form.Group controlId="lastName">
<Form.Label>Last Name</Form.Label>
<Form.Control
type="text"
placeholder="Enter last name"
name="lName"
onChange={this.handleOnChange.bind(this)}
/>
</Form.Group>
<div>
<button
variant="primary"
type="submit"
className="btn btn-primary mx-1"
>
Submit
</button>
<button variant="primary" type="reset" className="btn btn-warning">
Clear
</button>
</div>
<hr />
<br />
<div>
<Form.Group controlId="id">
<Form.Label>Id</Form.Label>
<Form.Control
type="text"
placeholder="Enter id"
name="id"
onChange={this.handleOnChange.bind(this)}
/>
</Form.Group>
<button variant="primary" className="btn btn-warning mx-1" onClick={this.handleOnSearch.bind(this)}>
Search
</button>
</div>
</Form>
</div>
);
}
}
export default App;
my server.js:
// Creating the express app
var express = require('express');
var app = express();
// Getting mysql database access
var mysql = require('mysql');
// Enabling support to the Cross-Origin Resource Sharing protocol
var cors = require('cors');
app.use(cors());
// Extracting the body of the req to expose it on command
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Writing connection details
var con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'reactmysql'
})
// Connecting to the database
con.connect((err) => {
if (err) {
console.log("There was an error connecting to the database: " + err);
}
console.log("Connected to the database");
})
// Starting listening on port 3001
app.listen(3001, () => {
console.log("I am listening on port 3001");
})
// Getting the data from the body whenever user inputs them and assigning them to backend variables
app.post('/', (req, res) => {
// var fName = req.body.user.fName
// var lName = req.body.user.lName
console.log(req);
console.log(res);
// var sql = "INSERT INTO ('firstname', 'lastname') VALUES ('" + fName + "', '" + lName + "')"
var sql = "SELECT * FROM `mytable`";
con.query(sql, (err, result) => {
if (err) {
console.log("There was an error in your query: " + err);
}
console.log("Query Executed Successfully");
console.log(result)
})
})
Add the express host in package.json of react app
"proxy": "http://localhost:3001/"
app.js
//GET Request
handleOnSearch() {
axios.get(`/${this.state.id}`
})
.then(res => {
console.log(this.state.persons);
this.setState({ persons: res.data });
});
}
server.js
app.get('/:id', (req, res) => {
const id = req.params.id;
//Rest of the code
})
edit
You can try this with your old code
In app.js add preventDefault()
handleOnSearch(event) {
event.preventDefault();
axios
.get(`http://localhost:3001`, {
params: {
id: this.state.id,
},
})
.then((res) => {
console.log(this.state.persons);
this.setState({ persons: res.data });
});
}
server.js
app.get('/', (req, res) => {
const id = req.query.id;
//Rest of the code
})
Use this with all handling.
axios.get('/:id', {
params: {
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});