react js show image from mysql with multer - mysql

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.

Related

ReactJS Upload picture (multer), store in MySQL, then display it

Im using reactJs,
Im working in localhost.
I managed to upload the picture,
Impossible to display the picture after the upload.
I managed to show the post data but not the picture
Here how I tried to display the picture :
{/* <img src="./16644430197124927082.png" alt='postimage'/> */}
{/* <img src={`${SERVER}`} alt="postimage"/> */}
{/* <img src={`${req.protocol}://${req.get('host')}/images/16644430197124927082.png`} /> */}
<div> <img src={val.image} alt="postphoto" /> </div>
Post.js (to get the data)
const express = require('express')
const router = express.Router()
const db = require('../config/db')
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { resolve } = require('path');
var storage = multer.diskStorage({
destination: 'client/src/images/',
filename: function (req, file, callback) {
callback(null, Date.now() + file.originalname);
}
});
var upload = multer({ storage: storage });
router.post('/upload', upload.single("file"), function (req, res, file) {
console.log(req.file, req.body);
const post = req.body.name;
const image = `${req.protocol}://${req.get('host')}/src/images/${req.file.filename}`;
console.log(image);
const username = req.body.username;
db.query(
"INSERT INTO post (post, image, username) VALUES (?, ?, ?);", [post, image, username],
(err, results) => {
console.log(err);
res.send(results);
}
);
});
router.get("/", (req, res) => {
db.query(
"SELECT * FROM socialmedia.post;",
(err, results) => {
console.log(err);
res.send(results);
}
);
});
Home.js (to display the data)
function Home() {
const [uploads, setUploads] = useState([]);
const [likes, setLikes] = useState([]);
useEffect(() => {
if (!localStorage.getItem("loggedIn")) {
localStorage.setItem("loggedIn", false);
}
}, []);
const getData = () => {
Axios.get("http://localhost:3001/post").then((response) => {
setUploads(response.data);
// response.data.map((val)=> {
// setLikes([...likes, val.likes]);
// });
});
console.log(likes);
}
useEffect(() => {
if (localStorage.getItem("loggedIn") === "true") {
getData(); } else {
alert("vous devez ĂȘtre connectĂ© pour afficher ce contenu!");
window.location.href = "/login";
}
}, []);
const likePost = (id) => {
Axios.post("http://localhost:3001/post/like", { userLiking: localStorage.getItem('username'), postid: id }).then((response) => {
console.log("You liked this post", response);
getData();
});
};
const editPost = (id) => {
window.location.href = `/edit/${id}`;
console.log(id);
};
return (
<div className='home'>
{uploads.map((val) => {
return (
<div className='post'>
<div className='user'>{val.username}</div>
<div className='content'>{val.post}</div>
{/* <img src="./16644430197124927082.png" alt='postimage'/> */}
{/* <img src={`${SERVER}`} alt="postimage"/> */}
{/* <img src={`${req.protocol}://${req.get('host')}/images/16644430197124927082.png`} /> */}
<div> <img src={val.image} alt="postphoto" /> </div>
<ThumbUpAltIcon
id="likeButton"
onClick={() => {
likePost(val.id);
}}
/>
{val.likes}
<button onClick={() => {
editPost(val.id);
}}>modifier ce post</button>
{/* <div><img src="./../images/1665482108659ae7dcd7bcb1861f88999f1277775df23.jpg" alt="postphoto" /> </div> */}
</div>
)
})}
</div>
)
};
export default Home

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

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.

How to display all single data from database? This is React

This is the profile page it shows all the data but I want to show only one data database after login?
function
function Profile() {
const [studentList, setStudentList] = useState([]);
let navigate = useNavigate();
const getStudent = () => {
Axios.get("http://localhost:3001/students").then((response) => {
setStudentList(response.data);
});
};
Display
return (
<div className="students">
<button onClick={getStudent}>Show Students</button>
<h3>
</h3>
{studentList.map((val, key) => {
return (
<div className="student">
<div>
<h3>Email: {val.email}</h3>
<h3>Password: {val.password}</h3>
<h3>Student Number: {val.student_num}</h3>
</div>
Get data from Database
app.get("/students", (req, res) => {
db.query("SELECT * FROM student", (err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
});
});

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 } }
})

How to filter date range in reactjs and dynamic data rendering

I want to dynamically render the data when filtering from start to end. The logic only displays one date value at a time. I want to display the E_NodeB Cell_Name Date E_RAB_Setup_Success_Rate Data_Traffic_DL Data_Traffic_UL UL_Throughput when I filter the from and to dates
`const data = "http://localhost:8080/sites";
const SelectSingle = () => {
var traffic = [];
var rab = [];
var newData = [];
const [sites, setsites] = useState([]);
const [selectedSite, setSelectedSite] = useState([]);
const [startDate, setDate] = useState();
const [endDate, setEndDate] = useState();
// 1
const handleChange = (event) => {
event.preventDefault();
const siteSelected = event.target.value;
const itemSelected = sites.filter(
(site) => site.Cell_Name === siteSelected
);
setSelectedSite(itemSelected);
};
// Start Date
// Traffice_Date
const handleDate = (e) => {
e.preventDefault();
const siteSelected = "4G_ADONKIA-2";
const dateChosen = sites.filter((site) => {
return (
site.Traffice_Date === getDate(e) && site.Cell_Name === siteSelected
);
});
newData.push(dateChosen);
setSelectedSite(dateChosen);
};
// End date
const handleEndDate = (e) => {
e.preventDefault();
const siteSelected = "4G_ADONKIA-2";
const dateChosen = sites.filter((site) => {
return (
site.Traffice_Date === getDate(e) && site.Cell_Name === siteSelected
);
});
setSelectedSite(dateChosen);
};
// Get Date Function
const getDate = (e) => {
const start = e.target.value;
const [year, month, day] = start.split("-");
const newDate = `${day}/${month}/${year}`;
return newDate;
};
useEffect(() => {
fetch(data)
.then((res) => res.json())
.then((data) => setsites(data));
});
selectedSite.map((site) => {
rab.push(site.E_RAB_Setup_Success_Rate);
traffic.push(site.Traffice_Date);
});
const state = {
labels: traffic,
datasets: [
{
label: "E_RAB_Setup_Success_Rate",
backgroundColor: "rgba(75,192,192,1)",
borderColor: "rgba(0,0,0,1)",
borderWidth: 2,
data: rab,
},
],
};
return (
<div>
<div className="data-class">
<select
onChange={(e) => {
handleChange(e);
}}
>
{sites.map((site, index) => (
<option value={site.Cell_Name} key={index}>
{site.Cell_Name}
</option>
))}
</select>
<h2>From</h2>
<input
type="date"
value={startDate}
onChange={(e) => {
handleDate(e);
}}
name="startDate"
/>
<h2>To</h2>
<input
type="date"
value={endDate}
onChange={(e) => {
handleEndDate(e);
}}
name="endDate"
/>
</div>
<div>
<table>
<thead>
<tr>
<th>E_NodeB</th>
<th>Date</th>
<th>Cell_Name</th>
<th>E_RAB_Setup_Success_Rate</th>
<th>Data_Traffic_DL</th>
<th>Data_Traffic_UL</th>
<th>UL_Throughput</th>
</tr>
</thead>
{selectedSite.map((site, index) => (
<tbody key={index}>
<td>{site.eNodeB_Name}</td>
<td>{site.Cell_Name}</td>
<td>{site.Traffice_Date}</td>
<td>{site.E_RAB_Setup_Success_Rate}</td>
<td>{site.Data_Traffic_DL}</td>
<td>{site.Data_Traffic_UL}</td>
<td>{site.G_UL_Throughput_IK}</td>
</tbody>
))}
</table>
<Line
data={state}
options={{
title: {
display: true,
text: "Plot of E_RAB_Setup_Success_Rate",
fontSize: 20,
},
legend: {
display: true,
position: "right",
},
}}
/>
</div>
</div>
);
};
export default SelectSingle;
`
Backend code
const express = require("express");
const cors = require("cors");
const mysql = require("mysql2");
const app = express();
const connection = mysql.createConnection({
host: "localhost",
user: "a",
password: "123",
database: "aa",
});
connection.connect((err) => {
if (err) throw err;
console.log("Connected to MySQL Server!");
});
app.use(cors());
app.get("/", function (req, res) {
connection.query("SELECT * FROM africell_data LIMIT 10", (err, rows) => {
if (err) throw err;
res.json(rows);
});
});
app.get("/sites", function (req, res) {
connection.query(
`SELECT eNodeB_Name,Cell_Name,Traffice_Date,E_RAB_Setup_Success_Rate,Data_Traffic_DL,Data_Traffic_UL,G_UL_Throughput_IK FROM africell_data`,
(err, rows) => {
if (err) throw err;
res.json(rows);
}`enter code here`
);
});
app.listen(8080, (req, res) => {
console.log(`The app is connected on port 8080`);
});
enter image description here
It appears in your handleDate and handleEndDate functions, you're filtering only for sites which have the specified date (site.Traffice_Date === getDate(e)), which would explain why you're only seeing one date. Try updating the code in your filter block to look for all sites with date above or below your start and end dates, as desired.