How can I edit using MySQL , NodeJs, React Js, - mysql

I've been trying to figure this out for hours, but i think im doing it wrong. So what im basically doing is.
-> Fetch the specific user, and throw it into the placeholder -> which is working
but when I try to edit the information and then when i try to save it this error shows and then in my phpadmin, it saves a null. it seems that I can't connect the front and the backend.
sql: 'UPDATE users SET name = NULL, email = NULL, mobile = NULL WHERE id = ${id} '
Edit.jsx
import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
const EditUser = () => {
const navigate = useNavigate()
const [data, setData] = useState([])
const [inputs, setInputs] = useState([])
const { id } = useParams()
useEffect(() => {
const getUser = async () => {
const res = await axios.get(`http://localhost:5000/${id}`)
setData(res.data[0])
}
getUser()
}, [])
const handleSubmit = async () => {
try {
await axios.put(`http://localhost:5000/${id}`, inputs)
} catch (error) {
console.log(error)
}
}
const handleChange = (e) => {
setInputs({ ...inputs, [e.target.name]: e.target.value })
}
return (
<div>
<form
action=""
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
}}
onSubmit={handleSubmit}
>
<label htmlFor="">Name</label>
<input type="text" placeholder={data.name} onChange={handleChange} />
<label htmlFor="">Email</label>
<input type="text" placeholder={data.email} onChange={handleChange} />
<label htmlFor="">Mobile</label>
<input type="text" placeholder={data.mobile} onChange={handleChange} />
<button type="submit">save</button>
</form>
</div>
)
}
export default EditUser
backend.js
app.put('/:id', (req, res) => {
const id = req.params.id
const name = req.body.name
const email = req.body.email
const mobile = req.body.mobile
pool.query(
`UPDATE users SET name = ?, email = ?, mobile = ? WHERE id = ${id} `,
[name, email, mobile],
(err, result) => {
if (err) {
console.log(err)
} else {
res.send(result)
}
}
)
})
app.get('/:id', (req, res) => {
const { name, email, mobile } = req.body
const { id } = req.params
pool.query(`SELECT * FROM users WHERE id = ${id} `, (err, result) => {
if (err) {
console.log(err)
} else {
res.send(result)
}
})
})

May be you should try :
The following states :
const EditUser = () => {
const navigate = useNavigate()
const [data, setData] = useState([])
const [name, setName] = useState("")
const [email, setEmail] = useState("")
const [mobile, setMobile] = useState("")
const { id } = useParams()
For your request :
const handleSubmit = async () => {
let datas ={
name: name,
email: email,
mobile: mobile
}
try {
await axios.put('http://localhost:5000/updateUser/'+id, datas)
} catch (error) {
console.log(error)
}
}
Then you just update your states that way :
<form
action=""
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
}}
onSubmit={handleSubmit}
>
<label htmlFor="">Name</label>
<input type="text" placeholder={data.name} onChange={()=>
{setName(e.currentTarget.value)} />
<label htmlFor="">Email</label>
<input type="text" placeholder={data.email} onChange={()=>
{setEmail(e.currentTarget.value)} />
<label htmlFor="">Mobile</label>
<input type="text" placeholder={data.mobile} onChange={()=>
{setMobile(e.currentTarget.value)} />
<button type="submit">save</button>
</form>
For you back end maybe you should add some informations in the adress (to avoid confusion with you app.get):
app.put('updateUser/:id', (req, res) => {
const id = req.params.id
const name = req.body.name
const email = req.body.email
const mobile = req.body.mobile
pool.query(
`UPDATE users SET name = ?, email = ?, mobile = ? WHERE id = ${id} `,
[name, email, mobile],
(err, result) => {
if (err) {
console.log(err)
} else {
res.send(result)
}
}
)
})
I hope it will help you !

I think I did it actually, but I dont know if this is the right method. so what i did is
instead of directing submit it as an await
const handleSubmit = async () => {
try {
await axios.put(`http://localhost:5000/${id}`, inputs)
} catch (error) {
console.log(error)
}
}
i did this.
const handleSubmit = async (e) => {
e.preventDefault()
try {
const res = await axios.put(`http://localhost:5000/${id}`, inputs)
setInputs(res.data)
} catch (error) {
console.log(error)
}}
Hey guys, if its wrong, please show me the other way.

Related

react js show image from mysql with multer

I'm working currently on a website where a user should be able to upload an image.
But unfortunately I get this error: GET c:\fakepath\nfr.jpeg net::ERR_UNKNOWN_URL_SCHEME
I'm using Express and multer.
Here's the code for my backend:
const storage = multer.diskStorage({
destination: (req, file, callBack) => {
callBack(null, './public/') // './public/images/' directory name where save the file
},
filename: (req, file, callBack) => {
callBack(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
const upload = multer({
storage: storage
})
app.get('/api/get', (req, res) => {
db.query(
'SELECT * FROM users',
(err, result) => {
if (err) {
console.log(err)
}
res.send(result)
}
)
})
app.post('/api/create', (upload.single('image')), (req, res) => {
const title = req.body.title
const post = req.body.post
const imagesrc = req.body.image
db.query(
'INSERT INTO users (title, post_text, images) VALUES (?,?,?)', [title, post, imagesrc],
(err, result) => {
if (err) {
console.log(err)
}
console.log(result)
}
)
})
Here's my code for the frontend:
const [title, setTitle] = useState('')
const [post, setPost] = useState('')
const [image, setImage] = useState('')
const submitPost = () => {
axios.post('http://localhost:3001/api/create', {
title: title,
post: post,
image: image,
}).then(r => {
console.log(r)
}).catch(err => {
console.log(err)
})
}
const [postList, setPostList] = useState([])
useEffect(() => {
axios.get('http://localhost:3001/api/get').then((data) => {
console.log(data)
setPostList(data.data)
})
}, [])
<div className="createPost">
<input
type='file'
name='file'
onChange={(e) => {
setImage(e.target.value)
}}
/>
<img src={image}/>
<input
type="text"
placeholder="Titel"
onChange={(e) => {
setTitle(e.target.value)
}}
/>
<input
type="text"
placeholder="Post"
onChange={(e) => {
setPost(e.target.value)
}}
/>
</div>
<div className="postButton">
<button onClick={submitPost}>speichern</button>
</div>
<div className="post">
{postList.map((val, key) => {
return (
<div className="Post" key={key}>
<h1>{val.title}</h1>
{/*<p>{val.username}</p>*/}
<p>{val.post_text}</p>
<p>{val.image}</p>
<button className="kaufenButton" onClick={toggleModalUnt}>Jetzt testen</button>
</div>
)
})}
</div>
If you need anything else, let me know it.
Thanks in advance.

ReactJS NodeJs after delete method everything stop working

Hello i was worked on crud app everything is worked fine but when i create delete route i cannot post data to server i get empty string and error cannot get if i follow get link i try to comment all delete methods but still no one is working even toast are stopped working works only navigate buttons ..
Server
index.js
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mysql = require("mysql");
const cors = require("cors");
var db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "crud_contact",
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/api/get", function(req,res){
console.log('Hello');
db.query('SELECT * FROM contact_db', function (error, result) {
res.send(result);
});
});
app.post("/api/post", (req, res) => {
const {name, email, contact} = req.body;
const sqlInsert =
`INSERT INTO contact_db (name,email, contact)
VALUES (?, ?, ?)`;
db.query(sqlInsert, [name, email, contact], (error,result) => {
res.send(result);
if(error) {
console.log(error);
}
});
})
// app.delete("/api/remove/:id", (req, res) => {
// const {id} = req.params;
// const sqlRemove =
// `DElETE FROM contact_db WHERE id = ?`;
// db.query(sqlRemove, id , (error,result) => {
// if(error) {
// console.log(error);
// }
// });
// })
//
app.get("/", (req, res) => {
// app.listen(5000, () => {
// con.connect(function(err) {
// if (err) throw err;
// console.log("Connected!");
// var sql = `INSERT INTO contact_db(name,email, contact)
// VALUES('popas','berazumis#gmail.com',8585858)`;
// con.query(sql, function (err, result) {
// if (err) throw err;
// console.log("record inserted");
// });
// });
// });
});
app.listen(5000, () => {
console.log("Listening port 5000");
});
Client
Add edit user
AddEdit.js
import React, { useState, useEffect } from "react";
import { useNavigate, useParams, Link } from "react-router-dom";
import "./AddEdit.css";
import axios from "axios";
import { toast } from "react-toastify";
const initiaState = {
name: "",
email: "",
contact: "",
};
const AddEdit = () => {
const [state, setState] = useState(initiaState);
const { name, email, contact } = state;
const navigate = useNavigate();
const handleSubmit = (e) => {
e.preventDefault();
if (!name || !email || !contact) {
toast.error("Please fill all labels below");
} else {
axios
.post("http://localhost:5000/api/post", {
name,
email,
contact
})
.then(() => {
setState({ name: "", email: "", contact: "" });
})
.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 style={{ marginTop: "100px" }}>
<form
style={{
margin: "auto",
padding: "15px",
maxWidth: "400px",
alignContent: "cener",
}}
onSubmit={handleSubmit}
>
<label htmlFor="name">Name</label>
<input
type="text"
id="name"
name="name"
placeholder="Type Name..."
value={name}
onChange={handleInputChange}
/>
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
name="email"
placeholder="Type Email..."
value={email}
onChange={handleInputChange}
/>
<label htmlFor="contact">Contact</label>
<input
type="number"
id="contact"
name="contact"
placeholder="Type contact number"
value={contact}
onChange={handleInputChange}
/>
<Link to="/">
<input type="submit" value="save" />
<input type="button" value="Go Back" />
</Link>
</form>
</div>
);
};
export default AddEdit;
Home.js
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import "./Home.css";
import { toast } from "react-toastify";
import axios from "axios";
const Home = () => {
const [data, setData] = useState([]);
const loadData = async () => {
const response = await axios.get("http://localhost:5000/api/get");
setData(response.data);
};
useEffect(() => {
loadData();
}, []);
/* const deleteContact = (id) => {
if(window.confirm("Are you sure that you wanna delete contact")) {
axios.delete(`http://localhost:5000/api/remove/${id}`);
toast.success("Contact Deleted Successfully");
setTimeout(() => loadData(), 500);
}
}
*/
return (
<div style={{ marginTop: "150px" }}>
<Link to="addContact">
<button className="btn btn-contact">Add contact</button>
</Link>
<table className="styled-table">
<thead>
<tr>
<th style={{ textAlign: "center" }}>No.</th>
<th style={{ textAlign: "center" }}>Name</th>
<th style={{ textAlign: "center" }}>Email</th>
<th style={{ textAlign: "center" }}>Contact</th>
<th style={{ textAlign: "center" }}>Action</th>
</tr>
</thead>
<tbody>
{data.map((item, index) => {
return (
<tr key={item.id}>
<th scope="row">{index + 1}</th>
<td>{item.name}</td>
<td>{item.email}</td>
<td>{item.contact}</td>
<td>
<Link to={`/update/${item.id}`}>
<button className="btn btn-edit" >Edit</button>
</Link>
<button className="btn btn-delete" /*onClick={() => deleteContact}*/ >Delete</button>
<Link to={`/view/${item.id}`}>
<button className="btn btn-view">View</button>
</Link>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
};
export default Home;
When you create a app.delete route, you no longer use POST method on your client side, you need to use the DELETE method.
Client Side Example
const res = await axios.delete('https://example.com/delete', { data: { answer: 42 } });
Server Side Example
app.delete('/delete', async(req, res,next) => {
console.log('req.body', req.body)
//prints { data: { answer: 42 } }
})

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

Change number of servings on click (React Hooks - API)

I'm working on a recipe site using API from a third party and want to change the number of servings (which is output from the API data) when clicking the + & - button. I tried assigning the output serving amount <Servings>{recipe.servings}</Servings> in a variable and useState to update it but it kept showing errors. I would appreciate any help (preferably using react Hooks). Thanks :)
Here is my code:
const id = 716429;
const apiURL = `https://api.spoonacular.com/recipes/${id}/information`;
const apiKey = "34ac49879bd04719b7a984caaa4006b4";
const imgURL = `https://spoonacular.com/cdn/ingredients_100x100/`;
const {
data: recipe,
error,
isLoading,
} = useFetch(apiURL + "?apiKey=" + apiKey);
const [isChecked, setIsChecked] = useState(true);
const handleChange = () => {
setIsChecked(!isChecked);
};
return (
<Section>
<h2>Ingredients</h2>
<ServingsandUnits>
{recipe && (
<ServingsIncrementer>
<p>Servings: </p>
<Minus />
<Servings>{recipe.servings}</Servings>
<Plus />
</ServingsIncrementer>
)}
<ButtonGroup>
<input
type="checkbox"
id="metric"
name="unit"
checked={isChecked}
onChange={handleChange}
/>
<label htmlFor="male">Metric</label>
</ButtonGroup>
</ServingsandUnits>
</Section>
};
My custom hook is called useFetch:
const useFetch = (url) => {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const abortCont = new AbortController();
fetch(url, { signal: abortCont.signal })
.then((res) => {
if (!res.ok) {
// error coming back from server
throw Error("Could not fetch the data for that resource");
}
return res.json();
})
.then((data) => {
setIsLoading(false);
setData(data);
setError(null);
})
.catch((err) => {
if (err.name === "AbortError") {
console.log("Fetch aborted");
} else {
// auto catches network / connection error
setIsLoading(false);
setError(err.message);
}
});
return () => {
abortCont.abort();
};
}, [url]);
return { data, isLoading, error };
};
export default useFetch;

I can't fetch react form

Hi I try to make simple contact from in react, but I stuck on fetch() method.
This is my code. I have no idea what is wrong.
FrontEnd
export default class ContactForm extends React.Component<IContactFormProps, any> {
constructor(props) {
super(props);
// local state
this.state = {
tl: new TimelineMax({paused: true, delay: 1}),
name: "",
email: "",
subject: "",
message: "",
sent: false,
}
this.handleOnSubmit = this.handleOnSubmit.bind(this);
this.handleClearForm = this.handleClearForm.bind(this);
this.handleChange = this.handleChange.bind(this);
this.startAnimation = this.startAnimation.bind(this);
}
handleOnSubmit(e) {
console.log("ContactForm->handleOnSubmit(e).");
e.preventDefault();
let formData = new FormData();
formData.append(name, this.state.name);
console.log("formData: " + formData);
fetch('/contact', {
method: 'POST',
body: formData
})
.then((response) => {
console.log("response: " + response);
console.log("response.ok: " + response.ok);
return response.json();
})
.then((responseJson) => {
console.log("responseJson: " + responseJson);
})
.catch((error) => {
console.log("error from fetch: " + error);
});
}
handleClearForm(e) {
console.log("ContactForm->handleClearForm(e).");
// e.preventDefault();
}
handleChange(event) {
const target = event.target;
const name = event.target.name;
const value = event.target.value;
this.setState({
[name]: value
});
// console.log("event.target.value: " + event.target.value);
// this.setState({value: event.target.value});
}
startAnimation() {
console.log("ContactForm->startAnimation().");
}
componentDidMount() {
this.startAnimation();
}
componentWillUnmount() {
}
render() {
return (
<form className="contact-form-cnt"
onSubmit={ this.handleOnSubmit }>
<div className="top-row">
<input type="text" name="name" placeholder="Name"
className="name" ref="name"
value={this.state.name} onChange={this.handleChange}/>
<input type="text" name="email" placeholder="Em#il"
className="email" ref="email"
value={this.state.email} onChange={this.handleChange}/>
</div>
<input type="text" name="subject" placeholder="Subject"
className="subject" ref="subject"
value={this.state.subject} onChange={this.handleChange}/>
<textarea name="message" placeholder="Write Your message here."
className="message" ref="message"
value={this.state.message} onChange={this.handleChange}></textarea>
<button type="submit" name="submit"
className="submit" ref="Send"
onClick={ this.handleClearForm }>Send</button>
</form>
);
};
};
BackEnd
'use strict';
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const winston = require('winston');
const distPath = path.join(__dirname, '../dist');
const indexFileName = 'index.html';
const app = express();
const PORT = process.env.PORT || 8080;
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(express.static(distPath));
app.get('*', (req, res) => res.sendFile(path.join(distPath, indexFileName)));
app.post("/contact", (req, res) => {
try {
console.log("mail sending succes!");
}
catch ( error ) {
console.log("mail sending failure!");
}
});
app.listen(PORT, (err) => {
if (err) {
winston.error(err);
return;
}
winston.info(`Listening on port ${PORT}`);
});
URL:
http://localhost:8080/contact
and error
POST http://localhost:8080/contact 404 (Not Found)
I think it's something with url, but I'am out of ideas. Any sugestions?
try something like this:
app.post("/contact", (req, res) => {
res.json({"foo": "bar"});
});
this way you are setting an json object as result. Let me know if works.