Not able post data from useState to Mysql - mysql

I am trying to post the input data from useState to Mysql but its just not happening. While I am able to get the data from the database to the page but when it comes to posting I don't know how to send data from state hooks to mysql when there are many values. Please take a look
Code from where i am sending the form data
import React,{useState , useRef} from "react";
import "./AddProjects.css"
import axios from "axios";
import Projects from "../Projects/Projects";
import {BiChevronLeftCircle,BiChevronRightCircle} from "react-icons/bi"
export default function AddProjects() {
const [AddProjects,setAddProjects] = useState({
ProjectName:"",
Discription:"",
git:"",
Img:""
})
const [getQuery,setGetQuery] = useState({
projectList:[]
})
const inputFile = useRef(null)
function handleChange(e) {
const {name , value} = e.target;
setAddProjects(newProjects => ({
...newProjects,[name]:value
}))
}
function imgChange(e) {
setAddProjects({ ...AddProjects, Img: URL.createObjectURL(e.target.files[0]) });
}
function getProjectList() {
axios.get(`http://localhost:3060/projects`)
.then((response) => response.data)
.then(response2 => {
setGetQuery({projectList : response2})
})
}
function onSubmitHandler(e) {
axios.post(`http://localhost:3060/addProjects`,{
ProjectName: AddProjects.ProjectName,
Discription:AddProjects.Discription,
git:AddProjects.git,
Img:AddProjects.Img
})
getProjectList()
}
return(
<>
<div className="AddProjects">
<form onSubmit={onSubmitHandler} method="POST" encType="multipart/form-data" >
<h2>Add New Project</h2>
<input type="text" placeholder="Project Name..." name="ProjectName" onChange={handleChange}/>
<input type="text" placeholder="Project Discription..." name="Discription" onChange={handleChange}/>
<input type="text" placeholder="Git Repository/Code..." name="git" onChange={handleChange}/>
<input type="file" accept="image/jpg,image/jpeg" name="Img" onChange={imgChange} ref={inputFile} />
<button type="button"onClick={() => inputFile.current.click()}>Add New Image</button>
<button type="submit" >Submit Project</button>
</form>
<button onClick={getProjectList}>click me </button>
</div>
<div>
<div className="Section-Projects" >
<h1>My Projects </h1>
{/* <Link to={checkBox?'/AddProjects':""} ><button className="Add-newProject" onClick={onStateChange}><IoIosAddCircleOutline/></button></Link> */}
<div className="Projects">
<button className="arrowLeft"><BiChevronLeftCircle /></button>
<div className="Single">
{getQuery.projectList.map((gettingQuery) =>
<Projects
ProjectId={gettingQuery.ProjectId}
ProjectName={gettingQuery.ProjectName}
Discription={gettingQuery.Discription}
git={gettingQuery.git}
Img={gettingQuery.Img}
/>
)}
</div>
<button className="arrowRight"><BiChevronRightCircle /></button>
</div>
</div>
</div>
</>
)
};
As you can see i want to send 4 things to the mysql table but i don't think the this is the way to do it and i just can't figure it out
Code for my file that is sending data
const express = require('express');
const cors = require('cors')
const PORT = 3060;
const db = require('./Database')
const bodyParser = require('body-parser');
const { response } = require('express');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.get('/projects', (req,res) => {
const TASK_QUERY = `SELECT * FROM addprojects.newproject`;
db.query(TASK_QUERY , (err, response) => {
if(err) res.status(404).send('somthings wrong')
else res.send(response)
})
});
app.post('/addProjects', (req,res) => {
const ADD_QUERY = `INSERT INTO addprojects.newproject VALUES('${req.body.data}')`;
db.query(ADD_QUERY, (err) => {
if (err) console.log(err)
else res.send('Query added sucsessfully')
})
} );
app.listen(PORT, () => {
console.log('app is listning to port 3000')
})
I think while the post method is correct the Value is not so please help I am on this for 2 days Any suggestion will be help full

INSERT INTO tablename (columnName1, columnName2) VALUES ('Company Inc', 'Highway 37')
For backend:
You don't mention the columns name, it doesn't know which field belongs to which column in the table.
For Frontend:
axios.post(`http://localhost:3060/addProjects`,{
ProjectName: AddProjects.ProjectName,
Discription:AddProjects.Discription,
git:AddProjects.git,
Img:AddProjects.Img
})
ProjectName,Discription,git,Img make these keys name exact to your column names.
And you are uploading an image in this api so convert your data from front in formdata then pass that data in api and on backend you will that data in formdata

Related

Not able to delete my column from my Mysql table

I tried everything I think but no able to delete data from my mysql table using axios.delete with ProjectId (table ids).
Here's my code for where I declared my function, and as you can see I am passing the function through props
import React from "react";
import Projects from "../Projects/Projects";
import "./pluseProjects.css";
import {IoIosAddCircleOutline} from "react-icons/io"
import { Link } from "react-router-dom";
import {BiChevronLeftCircle,BiChevronRightCircle} from "react-icons/bi"
import {IoRefreshCircleOutline} from "react-icons/io5";
import axios from "axios";
export default function PluseProjects() {
const [addNewProjects, setAddNewProjects ] = React.useState(false)
const [getQuery,setGetQuery] = React.useState({
projectList:[]
})
function onStateChange() {
setAddNewProjects(!addNewProjects)
}
function getProjectList() {
axios.get(`http://localhost:3060/projects`)
.then((response) => response.data)
.then(response2 => {
setGetQuery({projectList : response2})
})
}
function onDeleteId(ProjectId) {
axios.delete(`http://localhost:3060/deleteprojects/${ProjectId}`)
getProjectList();
}
return(
<div className="Section-Projects" >
<div className="top-projects">
<h1>My Projects </h1>
<button onClick={getProjectList} className="Refresh"><IoRefreshCircleOutline /></button>
<Link to={addNewProjects?'/AddProjects':""} ><button className="Add-newProject" onClick={onStateChange}><IoIosAddCircleOutline /></button></Link>
</div>
<div className="Projects">
<button className="arrowLeft"><BiChevronLeftCircle /></button>
<div className="Single">
{getQuery.projectList.map((gettingQuery) =>
<Projects
onHandleDelete={onDeleteId(gettingQuery.ProjectId)}
ProjectName={gettingQuery.ProjectName}
Discription={gettingQuery.Discription}
git={gettingQuery.git}
Img={gettingQuery.Img}
/>
)}
</div>
<button className="arrowRight"><BiChevronRightCircle /></button>
</div>
</div>
)
};
Here is my server.js code - I am telling SQL to delete this column with some ProjectId:
const express = require('express');
const cors = require('cors')
const PORT = 3060;
const db = require('./Database')
const bodyParser = require('body-parser');
const { response } = require('express');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.get('/projects', (req,res) => {
const TASK_QUERY = `SELECT * FROM newproject`;
db.query(TASK_QUERY , (err, response) => {
if(err) res.status(404).send('something is wrong')
else res.send(response)
})
});
app.post('/addProjects', (req,res) => {
const ADD_QUERY = `INSERT INTO newproject (ProjectName,Discription,git,Img) VALUES('${req.body.ProjectName}','${req.body.Discription}','${req.body.git}','${req.body.Img}')`;
db.query(ADD_QUERY, (err) => {
if (err) console.log(err)
else res.send('Query added successfully')
})
} );
app.delete('/deleteprojects/:ProjectId', (req,res) => {
console.log(req.params.ProjectId)
const DELETE_TASK = `DELETE FROM newProjects WHERE ProjectId = ${req.params.ProjectId}`
db.query(DELETE_TASK, (err,res) => {
if (err) console.log(err)
})
})
app.listen(PORT, () => {
console.log('app is listening on port 3000')
})
And here's where I am calling my function - I think my props management is all right. Am I calling the function the wrong way?
import React from "react";
import "./Projects.css"
import {RxCrossCircled} from "react-icons/rx"
export default function Projects(props) {
return(
<div className="Project" >
<div className="Image">
<img src={props.Img} alt=""/>
<button className="cross" onClick={props.ProjectId}><RxCrossCircled /></button>
</div>
<div className="Bottom">
<h3>{props.ProjectName}</h3>
<p>{props.Discription}</p>
{props.git}
</div>
</div>
)
};
If you see a http call in the network tab when you trigger the function (clicking the delete button etc). That means your frontend(react part) is working fine. Also i clearly see that you are missing an res.send() statement in your delete route in your server.js.
app.delete('/deleteprojects/:ProjectId', (req, res) => {
console.log(req.params.ProjectId)
const DELETE_TASK = `DELETE FROM newProjects WHERE ProjectId = ${req.params.ProjectId}`
db.query(DELETE_TASK, (err, res) => {
if (err) console.log(err)
res.status(200).send({}) // you missed this
})
})
Your onHandleDelete is not being used in the Projects component. And the ProjectId is not passed as a prop. In the PluseProjects you immediately call the onDeleteId function you should call it via an anonymous function.
PluseProjects
{
getQuery.projectList.map((gettingQuery) => (
<Projects
onHandleDelete={() => onDeleteId(gettingQuery.ProjectId)} // () =>
ProjectName={gettingQuery.ProjectName}
Discription={gettingQuery.Discription}
git={gettingQuery.git}
Img={gettingQuery.Img}
/>
));
}
Projects
export default function Projects(props) {
return (
<div className="Project">
<div className="Image">
<img src={props.Img} alt="" />
<button className="cross" onClick={props.onHandleDelete}> // change ProjectId to onHandleDelete
<RxCrossCircled />
</button>
</div>
<div className="Bottom">
<h3>{props.ProjectName}</h3>
<p>{props.Discription}</p>
{props.git}
</div>
</div>
);
}

How to send form data together with file to mysql

Hello so i'm working on project which user can input data and upload file through form. I made this project with react js, node, express, and using mysql as database. Im currently having a problem to input name and upload file simultaneously. How to uplaod the data and file together with one button. sry for bad english
App.js
import React,{ useState, useEffect} from 'react';
import './App.css';
import Axios from 'axios';
function App() {
const [invoice, setInvoice] = useState("");
const [date, setDate] = useState ("");
const [currency, setCurrency] = useState ("IDR");
const [amount, setAmount] = useState("");
const [title, setTitle] = useState("");
const [path, setPath] = useState("");
const [attachment, setAttachment] = useState("");
const [dataList, setDataList] = useState([]);
useEffect(() => {
Axios.get('http://localhost:3001/api/get').then((response)=> {
setDataList(response.data);
})
})
const submitData = () => {
Axios.post('http://localhost:3001/api/insert', {
Invoice_No: invoice,
Invoice_Date: date,
Curr: currency,
Amount: amount,
Supplier: title,
Path: path
})
}
return (
<div className="App">
<p>CRUD Applicaiton</p>
<div className="formControl">
<label>Invoice No</label>
<input type="number" onChange={(e)=> {
setInvoice(e.target.value);
}} />
<label>Invoice Date</label>
<input type="date" onChange={(e)=> {
setDate(e.target.value);
}} />
<label>Currency</label>
<select onChange={(e)=> {
setCurrency(e.target.value);
}}>
<option value="IDR">IDR</option>
<option value="USD">USD</option>
<option value="YEN">YEN</option>
</select>
<label>Amount</label>
<input type="number" onChange={(e)=> {
setAmount(e.target.value);
}} />
<label>Title</label>
<input type="text" onChange={(e)=> {
setTitle(e.target.value);
}} />
<button onClick={submitData}>Add Data</button>
<button type='reset'>Reset</button>
</div>
<div>
<form method='POST' encType='multipart/form-data' action='http://localhost:3001/api/upload'>
<input type="file" name="DocumentFile" />
<button>ADD to DB</button>
</form>
</div>
</div>
);
}
export default App;
index.js
const express = require('express');
const fs = require('fs');
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
const mysql = require('mysql');
const exphbs = require('express-handlebars');
const multer = require("multer")
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "",
database: "work"
});
const upload = multer({storage:multer.memoryStorage()});
app.use(cors());
app.use(express.json() || express.static(".public") || express.static(".upload"));
app.use(bodyParser.urlencoded({extended: true}));
app.get("/api/get", (req, res) => {
const sqlSelect= "SELECT * FROM invoice"
db.query(sqlSelect, (err, result)=>{
res.send(result);
});
})
app.post("/api/insert", (req, res) => {
const Invoice_No = req.body.Invoice_No
const Invoice_Date = req.body.Invoice_Date
const Currency = req.body.Curr
const Amount = req.body.Amount
const Title = req.body.Supplier
const sqlInsert = "INSERT INTO invoice(Invoice_No, Invoice_Date, Curr, Amount, Supplier) VALUES (?,?,?,?,?)"
db.query(sqlInsert, [Invoice_No, Invoice_Date, Currency, Amount, Title], (err, result)=>{
console.log(err)
});
})
app.post("/api/upload", upload.single('DocumentFile'), (req, res) => {
const Path = req.file.buffer.toString('base64')
q = "INSERT INTO invoice (Path) VALUES (?)"
db.query(q, [Path], (err, result) => {
console.log(Path)
})
})
app.listen(3001, ()=> {
console.log('running on port 3001')
});

Cloudinary React attachment upload is very slow

I have a file upload feature using Cloudinary in my React app. When I uploaded the file, it is saved to both Cloudinary and MySQL. I managed to upload things including PDF documents, however the upload is very slow. It takes more than 10 seconds to redirect to a new page after a successful upload. I am just wondering how I could improve it since it is affecting my system's performance.
Front-end
import React, {useState, useContext} from 'react'
import {Form, Button, Card} from 'react-bootstrap'
import Axios from 'axios';
import { useHistory } from 'react-router-dom';
function AddAttachment() {
const history = useHistory();
const [fileSelected, setFile] = useState();
const uploadImage = async(e) => {
e.preventDefault();
const formData = new FormData();
formData.append("file", fileSelected);
formData.append("upload_preset", "xxxxx");
const r = await Axios.post("https://api.cloudinary.com/v1_1/xxxxxx/image/upload", formData).then((response) => {
Axios.post("http://localhost:3001/uploadattachment",{
imageUrl: response.data.secure_url,
}).then(() => {
window.alert('You have successfully uploaded an image!');
history.push(`/viewproject`);
})
})
}
return (
<div className="d-flex justify-content-center">
<Card style={{ width: '70%' }}>
<Form onSubmit={uploadImage} className = "m-3 p-5">
<Form.Group className="mb-3" controlId="image">
<h3>
Add new attachment
</h3>
<hr/>
<Form.Control type="file"
onChange={(event) => {
setFile(event.target.files[0]);
}}
/>
</Form.Group>
<div className = "d-flex flex-end justify-content-end align-items-end mt-3">
<div>
<Button type = "submit" style={{color:'white', backgroundColor:'#104271'}}>Save</Button>
</div>
</div>
</Form>
</Card>
</div>
)
}
export default AddAttachment
Back-end (NodeJS)
app.post("/uploadattachment", (req,res) => {
const url = req.body.imageUrl;
try{
const addPicture = "INSERT INTO project_attachment(project_attachment_url) VALUES (?);"
db.query(addPicture, url, (err, result) => {
res.send(result);
})
}
catch(err){
console.log(err);
}
})
Just wondering if there are any part of my codes that could be improved? Thank you!
I don't know if this will improve your performance, but it will improve your code.
I strongly recommend you to do the upload in your backend using the npm package that cloudinary has, also it has transform and optimization assets.
With this you will call to your backend and it will be the responsible of handling the files repository and database. And your front-end will be cleaner
Hope it helps you.
app.post("/uploadattachment", (req,res) => {
try{
const upload_result = await cloudinary.v2.uploader.upload(req.file, {upload_preset: req.preset});
const addPicture = "INSERT INTO project_attachment(upload_result.secure_url) VALUES (?);"
db.query(addPicture, url, (err, result) => {
res.send(result);
})
}
catch(err){
console.log(err);
}
})

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

How can I correct this error in ReactJS / NodeJS / MySQL?

Here is my App.js file (client side) :
import "./App.css";
import { useState } from "react";
import Axios from "axios";
function App() {
const [usernameReg, setUsernameReg] = useState("")
const [passwordReg, setPasswordReg] = useState("")
const register = () => {
Axios.post("https://localhost3001/register", {
username: usernameReg,
password:passwordReg,
}).then((response) => {
console.log(response);
});
};
return (
<div className="App">
<div className="information">
<h1>Register</h1>
<label>Name:</label>
<input
type="text"
onChange={(e) => {
setUsernameReg(e.target.value);
}}
/>
<label>Password:</label>
<input
type="text"
onChange={(e) => {
setPasswordReg(e.target.value);
}}
/>
<button onClick={register}>Register</button>
</div>
<div className="login">
<h1>Login</h1>
<label>Name:</label>
<input
type="text"
/>
<label>Password:</label>
<input
type="text"
/>
<button>Login</button>
</div>
</div>
);
}
export default App;
and this is my index.js file (server side) :
const app = express();
const mysql = require("mysql");
const cors = require("cors");
app.use(cors());
app.use(express.json());
const db = mysql.createConnection({
user: "x",
host: "here is my db IP",
password: "x",
database: "x",
});
db.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
app.post("/register", (req, res) => {
const username = req.body.username;
const password = req.body.password;
db.query(
"INSERT INTO test (username, password) VALUES (?,?)",
[username, password],
(err, result) => {
console.log(err);
}
);
});
app.listen(3001, () => {
console.log("Yey, your server is running on port 3001");
});
When I start my React app, no problem into the console, same when I start my index.js (console prints "Yey, your server is running on port 3001" and "Connected!" so there is no problem with the db connection).
But when I press the register button, there is no data sent to my DB and I have these messages in the Chrome DevTools :
POST https://localhost3001/register net::ERR_CONNECTION_TIMED_OUT
and
Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:84)
I have also in these DevTool (network window) :
Failed to load response data
What can I do to fix that please ?
You should change this line:
Axios.post("https://localhost3001/register", {
to this other
Axios.post("https://localhost:3001/register", {
You are missing a : to separate the url part (localhost) from the port 3001
use http://localhost:3001/register. Not https://localhost3001/register
From time to time we will make such silly mistakes :vvvv