How to display images - javascript

When I store my image in mysql it get stored as a blob and when i try to display it the image does not show up. I have tried to find how to display it but had no luck. Can anyone help me. The first piece of code is the form and the next piece which starts with const express is where the data gets sent to the mysql server.
import React, {Component} from "react";
import axios from "axios";
import {Redirect} from 'react-router-dom'
export default class Sell extends Component{
constructor(){
super()
this.state={
img:"",
dropdownval:'',
h:1
}
}
handleSubmit = e =>{
e.preventDefault()
const data={
tiTle:this.product,
descripTion:this.description,
condiTion:this.state.dropdownval,
quanTity:this.quantity,
prIce:this.price,
picTure:this.state.img
}
axios.post('http://localhost:3001/sell/listing',data).then(
res => {
console.log(res)
}
).catch(
err=>{
console.log(err)
}
)
this.setState({
h:0
})
}
onImageChange =(e)=>{
const [file] = e.target.files
this.setState({
img:URL.createObjectURL(file)
})
}
onDropdownChange =(e)=>{
this.setState({ dropdownval:e.target.value });
}
render(){
if(this.state.h===0){
return <Redirect to={'/'}/>
}
return(
<form className="sellForm" onSubmit={this.handleSubmit}>
<h3>Sell</h3>
<div className="form-group">
<label>Product Title</label>
<input type="text" className="form-control" required
onChange={e => this.product= e.target.value}/>
</div><br/>
<div className="form-group">
<label>Description</label><br/>
<textarea className="description" type="text" required
onChange={e => this.description= e.target.value}/>
</div><br/>
<label>Condition:</label><br/>
<select onChange={this.onDropdownChange}>
<option value="new">New</option>
<option value="slightly-used">Slightly Used</option>
<option value="used">Used</option>
</select>
<div className="form-group">
<br/><label>Quantity:</label><br/>
<input className="form-control" type="number" min="0" required
onChange={e => this.price= e.target.value}/>
</div><br/>
<div className="form-group">
<label>Price:</label><br/>
<span>$</span>
<input className="form-control" type="number" min="0" required
onChange={e => this.quantity= e.target.value}/>
</div><br/>
<div className="form-group">
<br/><label className="img-label">Insert Image</label>
<input type="file" onChange={this.onImageChange}/>
<img className="sellImg"src={this.state.img}/>
</div><br/>
<button className="btn btn-primary btn-block">
Upload Listing
</button>
</form>
)
}
}
const express = require("express")
const bodyParser=require("body-parser")
const app = express();
const cors=require("cors")
const mysql = require("mysql");
app.post("/sell/listing",(req,res)=>{
const title = req.body.tiTle
const description = req.body.descripTion
const condition = req.body.condiTion
const quantity = req.body.quanTity
const price = req.body.prIce
const pic = req.body.picTure
sqlInsert="INSERT INTO listings (name,price,description,condi,quantity,picture) VALUES(?,?,?,?,?,?)"
db.query(sqlInsert,[title,price,description,condition,quantity,pic], (err,result)=>{
console.log(err)
})
})
app.get("/api/get", (req, res) => {
const sqlSelect = "SELECT * FROM listings";
db.query(sqlSelect, (err, result) => {
res.send(result)
})
})
app.listen(3001, () =>{
console.log("running on port 3001");
});
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "",
database: "cruddatabase",
})

Related

Why is my boolean statement always evaluating to true?

I'm pretty new to javascript, and I am trying to figure out how to calculate sales tax based off of US states. In my code, I attempted to use an if else statement based off of the input value of state to accomplish this. However, no matter what I put in for the value of state the tax is determined based off of 8.75%, and I'm not sure what I am doing wrong. I would really appreciate any help or advice on how to fix this problem.
Thank you
PlaceOrderScreen.js
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link } from 'react-router-dom';
import { createOrder } from '../actions/orderActions';
import CheckoutSteps from '../components/CheckoutSteps';
import { ORDER_CREATE_RESET } from '../constants/orderConstants';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';
export default function PlaceOrderScreen(props) {
const cart = useSelector((state) => state.cart);
if (!cart.paymentMethod) {
props.history.push('/payment');
}
const orderCreate = useSelector((state) => state.orderCreate);
const { loading, success, error, order } = orderCreate;
const toPrice = (num) => Number(num.toFixed(2)); // 5.123 => "5.12" => 5.12
cart.itemsPrice = toPrice(
cart.cartItems.reduce((a, c) => a + c.qty * c.price, 0)
);
//Sales Tax//
{
if (cart.shippingAddress.state === 'New York'||'NY'){
cart.taxPrice = toPrice(0.0875 * cart.itemsPrice)}
else if (cart.shippingAddress.state === 'Kansas'||'KS') {
cart.taxPrice = toPrice(0.065 * cart.itemsPrice)}
else {
cart.taxPrice = toPrice(0 * cart.itemsPrice)}
};
cart.totalPrice = cart.itemsPrice + cart.shippingPrice + cart.taxPrice;
const dispatch = useDispatch();
const placeOrderHandler = () => {
dispatch(createOrder({ ...cart, orderItems: cart.cartItems }));
};
useEffect(() => {
if (success) {
props.history.push(`/order/${order._id}`);
dispatch({ type: ORDER_CREATE_RESET });
}
}, [dispatch, order, props.history, success]);
return (
<div>
<CheckoutSteps step1 step2 step3 step4></CheckoutSteps>
<div className="row top">
<div className="col-2">
<ul>
<li>
<div className="card card-body">
<h2>Shipping</h2>
<p>
<strong>Name:</strong> {cart.shippingAddress.fullName} <br />
<strong>Address: </strong> {cart.shippingAddress.address},
{cart.shippingAddress.city}, {cart.shippingAddress.state}, {cart.shippingAddress.postalCode}
,{cart.shippingAddress.country}
</p>
</div>
</li>
</ul>
</div>
</div>
</div>
ShippingAddressScreen.js
import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { saveShippingAddress } from '../actions/cartActions';
import CheckoutSteps from '../components/CheckoutSteps';
export default function ShippingAddressScreen(props) {
const userSignin = useSelector((state) => state.userSignin);
const { userInfo } = userSignin;
const cart = useSelector((state) => state.cart);
const { shippingAddress } = cart;
if (!userInfo) {
props.history.push('/signin');
}
const [fullName, setFullName] = useState(shippingAddress.fullName);
const [address, setAddress] = useState(shippingAddress.address);
const [city, setCity] = useState(shippingAddress.city);
const [state, setState] = useState(shippingAddress.state);
const [postalCode, setPostalCode] = useState(shippingAddress.postalCode);
const [country, setCountry] = useState(shippingAddress.country);
const dispatch = useDispatch();
const submitHandler = (e) => {
e.preventDefault();
dispatch(
saveShippingAddress({ fullName, address, city, state, postalCode, country })
);
props.history.push('/payment');
};
return (
<div>
<CheckoutSteps step1 step2></CheckoutSteps>
<form className="form" onSubmit={submitHandler}>
<div>
<h1>Shipping Address</h1>
</div>
<div>
<label htmlFor="fullName">Full Name</label>
<input
type="text"
id="fullName"
placeholder="Enter full name"
value={fullName}
onChange={(e) => setFullName(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="address">Address</label>
<input
type="text"
id="address"
placeholder="Enter address"
value={address}
onChange={(e) => setAddress(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="city">City</label>
<input
type="text"
id="city"
placeholder="Enter city"
value={city}
onChange={(e) => setCity(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="state">State</label>
<input
type="text"
id="state"
placeholder="Enter state"
value={state}
onChange={(e) => setState(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="postalCode">Postal Code</label>
<input
type="text"
id="postalCode"
placeholder="Enter postal code"
value={postalCode}
onChange={(e) => setPostalCode(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="country">Country</label>
<input
type="text"
id="country"
placeholder="Enter country"
value={country}
onChange={(e) => setCountry(e.target.value)}
required
></input>
</div>
<div>
<label />
<button className="primary" type="submit">
Continue
</button>
</div>
</form>
</div>
);
}
Your code should look like this:
cart.shippingAddress.state === 'New York'|| cart.shippingAddress.state === 'NY'
Your current code is testing if the string "NY" is true or not, and that evaluates to true in your boolean test, so you're always getting the 8.75% tax rate.

How to display the logged in user details in a table format using session in node js , react js , sql?

This the view page where user details are redirected
Hello all currently i am working on a project which has two form login and user details form.
When users login and fills the details form after that it will redirect it to view page where he/she can view, edit ,delete his/her record. But when user login only his records should be seen. In my case it is fetching all the records in a view page. I am using session in node js. I don't know what's gone wrong.
Server code
const express = require("express");
const app = express();
const cors = require('cors');
const mysql = require("mysql");
const cookie=require("cookie-parser");
const session=require("express-session");
const bodyparser=require("body-parser");
app.use(cors({
origin:("http://localhost:3000"),
methods:("GET","POST"),
credentials:true
}));
app.use(cookie("secret"));
app.use(bodyparser.urlencoded({extended:true}));
app.use(session({
key:"userid",
resave:false,
saveUninitialized:false,
secret:"userinfo",
cookie:{
expires:60*60*24,
},
}))
app.use(express.json());
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'demo'
});
db.connect((err) => {
if (err) {
throw err;
}
else {
console.log("Mysql Connected");
}
})
//var sess
app.post('/register', (req, res) => {
const email = req.body.email;
const password = req.body.password;
const cpassword = req.body.cpassword;
db.query("SELECT FROM registration WHERE email='"+email+"';", [email], (err, result) => {
if(result){
res.send({message:"User already exists"})
}
else{
db.query("INSERT INTO registration (email,password,cpassword) VALUES(?,?,?)", [email, password, cpassword], (err, result) => {
if(err){
res.send(err);
}
else{
res.send({message:"Registered Successful"})
}
})
}
})
})
app.post("/login", (req, res) => {
const email = req.body.email;
const password = req.body.password;
db.query("SELECT * FROM registration WHERE email='"+email+"' AND password='"+password+"';", [email,password], (err, result) => {
if(err){
res.send({err:err});
}
if(result.length>0){
req.session.user=result;
console.log( req.session.user)
res.send(result);
// sess=req.session;
// sess.userid=req.body.email;
// console.log(req.session)
else{
res.send({message:"Wrong username/passsword"})
}
})
app.get("/login",(req,res)=>{
if(req.session.user){
res.send({loggedIn:true,user:req.session.user})
}
else{
res.send({loggedIn:false});
}
})
app.post('/add', (req, res) => {
const firstname=req.body.firstname;
const lastname=req.body.lastname;
const email=req.body.email;
const mobile=req.body.mobile;
const address=req.body.address;
const city=req.body.city;
const pincode=req.body.pincode;
const conference=req.body.conference;
const seminar=req.body.seminar;
const paper=req.body.paper;
//const user_id=req.body.user_id;
if(firstname==""||lastname==""||email==""||mobile==""||address==""||city==""||pincode==""||conference==""||seminar==""||paper=="")
{
return res.status(422).json({error:"Please Fill the form correctly"});
}
db.query("INSERT INTO teacher (firstname,lastname,email,mobile,address,city,pincode,conference,seminar,paper) VALUES(?,?,?,?,?,?,?,?,?,?)", [firstname,lastname,email,mobile,address,city,pincode,conference,seminar,paper], (err, result) => {
console.log(err)
// if(result){
// //sess=req.session;
// req.session.user=result;
// console.log(req.session.user)
// res.send(result)
//sess.email=req.body.email;
//if(sess.email){
//console.log( sess)
//res.send(result)
//res.redirect("/view");
//}
// }
// else{
// res.send(err)
// }
})
})
// })
//
app.get("/teachersdata" , (req, res) => {
db.query("SELECT * FROM teacher ",(err,result)=>{
if(result){
res.send(result);
}
})
app.get("/teachersdata/:id", (req, res) => {
db.query('SELECT * FROM teacher WHERE id=?',[req.params.id], (err, result)=>{
if(err){
console.log('Error while fetching employee by id', err);
}else{
res.send(result)
}
})
})
app.get("/logout",(req,res)=>{
console.log("logout page");
//req.logout()
console.log( req.session.user)
res.clearCookie("user")
//res.redirect("/login")
req.session.destroy((err) => {
res.redirect('/login') // will always fire after session is destroyed
})
})
})
app.put('/edit/:id',(req,res)=>{
const firstname=req.body.firstname;
const lastname=req.body.lastname;
const email=req.body.email;
const mobile=req.body.mobile;
const address=req.body.address;
const city=req.body.city;
const pincode=req.body.pincode;
const conference=req.body.conference;
const seminar=req.body.seminar;
const paper=req.body.paper;
const id=req.params.id;
db.query("UPDATE teacher SET firstname=?,lastname=?,mobile=?,email=?,address=?,city=?,pincode=?,conference=?,seminar=?,paper=? WHERE id=?",[id,firstname,lastname,email,mobile,address,city,pincode,conference,seminar,paper],(err,res)=>{
if(err){
console.log(err)
}
else{
res.send(res);
}
})
})
app.delete("/delete/:id",(req,res)=>{
db.query("DELETE FROM teacher WHERE id=?",[req.params.id],(result,err)=>{
if(err){
res.send(err)
}
else{
res.send(result)
}
})
})
app.listen(3001)
This is the react code
import React from 'react';
import axios from 'axios';
import { useState,useEffect } from 'react';
import { Link } from 'react-router-dom';
export const View = () => {
const [teacherList, setteacherList] = useState([]);
useEffect(() => {
loadUsers();
}, [])
const loadUsers= async()=>{
const result =await axios.get("http://localhost:3001/teachersdata");
console.log(result)
setteacherList(result.data)
}
const deleteUser = async id => {
await axios.delete(`/delete/${id}`);
loadUsers();
};
return (
<div>
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">FirstName</th>
<th scope="col">LastName</th>
<th scope="col">Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{
teacherList.map((user,index)=>(
<tr>
<th scope="row">{index+1}</th>
<td>{user.firstname}</td>
<td>{user.lastname}</td>
<td>{user.email}</td>
<td>
<Link class="btn btn-primary me-md-2" to={`/teachersdata/${user.id}`}>View</Link>
<Link class="btn btn-outline-primary me-md-2" to={`/edit/${user.id}`}>Edit</Link>
<Link class="btn btn-danger" onClick={() => deleteUser(user.id)}>Delete</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
login page (client)
import React from 'react'
import { useState } from 'react';
import axios from 'axios';
import {useHistory} from 'react-router-dom';
const Login = () => {
axios.defaults.withCredentials=true;
const history=useHistory();
const [emailreg,setemail]=useState('');
const [passreg,setpass]=useState('');
const login=()=>{
axios.post("/login",{
email:emailreg,
password:passreg,
}).then((res)=>{
//alert(res.data.message)
//setLoginUser(res.data.user)
//history.push("/add")
//console.log(res);
if(res.data.message){
alert(res.data.message);
}
else{
alert("Login Sucessfully");
history.push("/add")
}
})
}
return (
<div className="login">
<h1>Login</h1>
<label>Email ID</label>
<input type="text" onChange={(e)=>{
setemail(e.target.value);
}}/><br/>
<label>Password</label>
<input type="password" onChange={(e)=>{
setpass(e.target.value);
}}/><br/>
<button onClick={login}>Login</button>
</div>
)
}
export default Login
User details page
import { useState } from 'react'
import axios from 'axios';
import {useHistory} from 'react-router-dom';
import { useEffect } from 'react';
const Main = () => {
const [formStep, setFormStep] = useState(0);
const history=useHistory();
const [firstname,setfirstname]=useState('');
const [lastname,setlastname]=useState('');
const [email,setemail]=useState('');
const [mobile,setmobile]=useState('');
const [address,setaddress]=useState('');
const [city,setcity]=useState('');
const [pincode,setpincode]=useState('');
const [conference,setconference]=useState('');
const [seminar,setseminar]=useState('');
const [paper,setpaper]=useState('');
const [loginstatus,setlogin]=useState('');
//const [userid,setuserid]=useState('');
const completeFormStep = () => {
setFormStep(step => step + 1)
}
const backFormStep = () => {
setFormStep(step => step - 1)
}
const handlesubmit = () => {
axios.post("http://localhost:3001/add",{
firstname:firstname,
lastname:lastname,
email:email,
mobile:mobile,
address:address,
city:city,
pincode:pincode,
conference:conference,
seminar:seminar,
paper:paper,
//userid:userid
}).then((res)=>{
console.log("success");
})
history.push("/view")
};
useEffect(() => {
axios.get("/login").then((res)=>{
console.log(res)
if(res.data.loggedIn===true){
setlogin(res.data.user[0].email)
// if(res.data.loggedIn===true){
// setlogin(res.data.userid)
}
})
}, []);
return (
<div className="create">
<form method="POST">
{formStep === 0 && (
<section>
<h1>{"Welcome" + loginstatus}</h1>
<h2>Names</h2>
<label>First Name</label>
<input
type="text"
required
onChange={(e)=>{
setfirstname(e.target.value);
}}
/>
<br />
<label>Last Name</label>
<input
type="text"
required
onChange={(e)=>{
setlastname(e.target.value);
}}
/>
<br />
<button type="button" onClick={completeFormStep}>Next</button>
</section>)}
<div className="step2">
{formStep === 1 && (
<section>
<h2>Contact</h2>
<label>Email ID</label>
<input
type="email"
required
onChange={(e)=>{
setemail(e.target.value);
}}
/>
<br />
{/* <label>UserID</label>
<input
type="userid"
required
onChange={(e)=>{
setuserid(e.target.value);
}}
/>
<br/> */}
<label>Mobile No.</label>
<input
type="text"
required
onChange={(e)=>{
setmobile(e.target.value);
}}
/>
<br />
<button type="button" onClick={backFormStep}>Back</button>
<button type="button" onClick={completeFormStep}>Next</button>
</section>)}
</div>
<div className="step3">
{formStep === 2 && (
<section>
<h2>Address</h2>
<label>Address</label>
<textarea onChange={(e)=>{
setaddress(e.target.value);
}}>
</textarea>
<br />
<label>City</label>
<input
type="text"
required
onChange={(e)=>{
setcity(e.target.value);
}}
/>
<br />
<label>Pincode</label>
<input
type="text"
required
onChange={(e)=>{
setpincode(e.target.value);
}}
/>
<br />
<button type="button" onClick={backFormStep}>Back</button>
<button type="button" onClick={completeFormStep}>Next</button>
</section>)}
</div>
<div className="step4">
{formStep === 3 && (
<section>
<h2>Conferences attended,seminar and paper presented</h2>
<label>Conferences name</label>
<textarea placeholder="conferences names" onChange={(e)=>{
setconference(e.target.value);
}}></textarea>
<br />
<label>Seminar attended</label>
<textarea placeholder="seminar names"onChange={(e)=>{
setseminar(e.target.value);
}}></textarea>
<br />
<label>Paper presented</label>
<textarea placeholder="paper names" onChange={(e)=>{
setpaper(e.target.value);
}}></textarea>
<br />
<button type="button" onClick={backFormStep}>Back</button>
<button type="submit" onClick={handlesubmit}>Submit</button>
</section>)}
<div>
</div>
</div>
</form>
</div>
);
}
export default Main
I want that when user login and fills details form only his or logged in user details should be displayed each users should get their own details in the view page after login. I am new to node js and react.
Thanks in advance
I can see you are sending {loggedIn:true,user:req.session.user} after login but your client app ignores it now. What you can do is to save this object you receive after login on Local Storage so even if they refresh the page we will have access to the object.
After saving the object on local storage, in your Main component, you need to check if an object exists in the local storage and the loggedIn value is true and user session object has not expired. If any of these conditions are not met, you have to clear the local storage and redirect the user to login page.
I am not sure whether you have the expiry of session in the user object but you must have a cookie with expiry for sure.
I hope it's clear.

How to display user info after submitting the form to sql database in react js?

Hello all i am working on a project where i am able to register and login after the these two steps user have to fill one more form i.e. display below and then after submitting these form data is going to database but when i click on show on the next page it is displaying all the records. I want the records of current user filled in but it is showing all the records from sql database.
Main.js
import { useState } from 'react'
import axios from 'axios';
import {useHistory} from 'react-router-dom';
import { useEffect } from 'react';
const Main = () => {
const [formStep, setFormStep] = useState(0);
const history=useHistory();
const [firstname,setfirstname]=useState('');
const [lastname,setlastname]=useState('');
const [email,setemail]=useState('');
const [mobile,setmobile]=useState('');
const [address,setaddress]=useState('');
const [city,setcity]=useState('');
const [pincode,setpincode]=useState('');
const [conference,setconference]=useState('');
const [seminar,setseminar]=useState('');
const [paper,setpaper]=useState('');
const [loginstatus,setlogin]=useState('');
const completeFormStep = () => {
setFormStep(step => step + 1)
}
const backFormStep = () => {
setFormStep(step => step - 1)
}
const handlesubmit = () => {
axios.post("http://localhost:3001/add",{
firstname:firstname,
lastname:lastname,
email:email,
mobile:mobile,
address:address,
city:city,
pincode:pincode,
conference:conference,
seminar:seminar,
paper:paper
}).then((res)=>{
console.log("success");
})
history.push("/view")
};
useEffect(() => {
axios.get("http://localhost:3001/login").then((res)=>{
console.log(res)
if(res.data.loggedIn===true){
setlogin(res.data.user[0].email)
}
})
}, []);
return (
<div className="create">
<form method="POST">
{formStep === 0 && (
<section>
<h1>{"Welcome" + loginstatus}</h1>
<h2>Names</h2>
<label>First Name</label>
<input
type="text"
required
onChange={(e)=>{
setfirstname(e.target.value);
}}
/>
<br />
<label>Last Name</label>
<input
type="text"
required
onChange={(e)=>{
setlastname(e.target.value);
}}
/>
<br />
<button type="button" onClick={completeFormStep}>Next</button>
</section>)}
<div className="step2">
{formStep === 1 && (
<section>
<h2>Contact</h2>
<label>Email ID</label>
<input
type="email"
required
onChange={(e)=>{
setemail(e.target.value);
}}
/>
<br />
<label>Mobile No.</label>
<input
type="text"
required
onChange={(e)=>{
setmobile(e.target.value);
}}
/>
<br />
<button type="button" onClick={backFormStep}>Back</button>
<button type="button" onClick={completeFormStep}>Next</button>
</section>)}
</div>
<div className="step3">
{formStep === 2 && (
<section>
<h2>Address</h2>
<label>Address</label>
<textarea onChange={(e)=>{
setaddress(e.target.value);
}}>
</textarea>
<br />
<label>City</label>
<input
type="text"
required
onChange={(e)=>{
setcity(e.target.value);
}}
/>
<br />
<label>Pincode</label>
<input
type="text"
required
onChange={(e)=>{
setpincode(e.target.value);
}}
/>
<br />
<button type="button" onClick={backFormStep}>Back</button>
<button type="button" onClick={completeFormStep}>Next</button>
</section>)}
</div>
<div className="step4">
{formStep === 3 && (
<section>
<h2>Conferences attended,seminar and paper presented</h2>
<label>Conferences name</label>
<textarea placeholder="conferences names" onChange={(e)=>{
setconference(e.target.value);
}}></textarea>
<br />
<label>Seminar attended</label>
<textarea placeholder="seminar names"onChange={(e)=>{
setseminar(e.target.value);
}}></textarea>
<br />
<label>Paper presented</label>
<textarea placeholder="paper names" onChange={(e)=>{
setpaper(e.target.value);
}}></textarea>
<br />
<button type="button" onClick={backFormStep}>Back</button>
<button type="submit" onClick={handlesubmit}>Submit</button>
</section>)}
<div>
</div>
</div>
</form>
</div>
);
}
export default Main
Below the code where i want the details of current user by clicking on show
import React from 'react';
import axios from 'axios';
import { useState } from 'react';
//import { Link } from 'react-router-dom';
export const View = () => {
const [teacherList, setteacherList] = useState([]);
const showdata = () => {
axios.get("http://localhost:3001/teachersdata").then((response) => {
console.log(response)
setteacherList(response.data);
});
};
return(
<div>
{/* <Link to="/teacherdata/:emailId" onClick={showdata}>Show</Link> */}
<button type="submit" onClick={showdata}>Show</button>
{teacherList.map((val,key)=>{
return <div className='teacher'>
<h3>Name: {val.firstname}</h3>
<h3>Lastname: {val.lastname}</h3>
<h3>Email: {val.email}</h3>
<h3>Mobile: {val.mobile}</h3>
<h3>Address: {val.address}</h3>
<h3>City: {val.city}</h3>
<h3>Pincode: {val.pincode}</h3>
<h3>Conference: {val.conference}</h3>
<h3>Seminar: {val.seminar}</h3>
<h3>Paper Presented: {val.paper}</h3>
</div>
})}
<button>Download PDF</button>
</div>
)
}
This is my server side code i have use nodejs express js
onst express = require("express");
const app = express();
const cors = require('cors');
const mysql = require("mysql");
const cookie=require("cookie-parser");
const session=require("express-session");
const bodyparser=require("body-parser");
//const sessionteacher = require('express-mysql-session')(session);
app.use(cors({
origin:("http://localhost:3000"),
methods:("GET","POST"),
credentials:true
}));
app.use(cookie());
app.use(bodyparser.urlencoded({extended:true}));
app.use(session({
//teacher:sessionteacher,
key:"userid",
resave:false,
saveUninitialized:false,
secret:"userinfo",
cookie:{
expires:60*60*24,
},
}))
app.use(express.json());
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'typroject'
});
db.connect((err) => {
if (err) {
throw err;
}
else {
console.log("Mysql Connected");
}
})
app.post('/register', (req, res) => {
const email = req.body.email;
const password = req.body.password;
const cpassword = req.body.cpassword;
db.query("SELECT FROM registration WHERE email='"+email+"';", [email], (err, result) => {
if(result){
res.send({message:"User already exists"})
}
else{
db.query("INSERT INTO registration (email,password,cpassword) VALUES(?,?,?)", [email, password, cpassword], (err, result) => {
if(err){
res.send(err);
}
else{
res.send({message:"Registered Successful"})
}
})
}
})
})
app.post("/login", (req, res) => {
const email = req.body.email;
const password = req.body.password;
db.query("SELECT * FROM registration WHERE email='"+email+"' AND password='"+password+"';", [email,password], (err, result) => {
if(err){
res.send({err:err});
}
if(result.length>0){
req.session.user=result;
console.log( req.session.user)
res.send(result);
}
else{
res.send({message:"Wrong username/passsword"})
}
})
app.get("/login",(req,res)=>{
if(req.session.user){
res.send({loggedIn:true,user:req.session.user})
}
else{
res.send({loggedIn:false});
}
})
app.post('/add', (req, res) => {
const firstname=req.body.firstname;
const lastname=req.body.lastname;
const email=req.body.email;
const mobile=req.body.mobile;
const address=req.body.address;
const city=req.body.city;
const pincode=req.body.pincode;
const conference=req.body.conference;
const seminar=req.body.seminar;
const paper=req.body.paper;
if(firstname==""||lastname==""||email==""||mobile==""||address==""||city==""||pincode==""||conference==""||seminar==""||paper=="")
{
return res.status(422).json({error:"Please Fill the form correctly"});
}
db.query("INSERT INTO teacher (firstname,lastname,email,mobile,address,city,pincode,conference,seminar,paper) VALUES(?,?,?,?,?,?,?,?,?,?)", [firstname,lastname,email,mobile,address,city,pincode,conference,seminar,paper], (err, result) => {
console.log(err);
})
})
app.get("/teachersdata", (req, res) => {
db.query("SELECT * FROM teacher", (err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
});
});
app.get("/logout",(req,res)=>{
console.log("logout page");
//req.logout()
console.log( req.session.user)
res.clearCookie("userid")
//res.redirect("/login")
req.session.destroy((err) => {
res.redirect('/login') // will always fire after session is destroyed
})
})
})
app.listen(3001)
Thank you in advance
I think you want this:
app.get("/teachersdata/:emailId", (req, res) => {
db.query("SELECT * FROM teacher WHERE email=$1",[req.params.emailId]).then(result) => {
if(!result || result.rows[0]) return console.log('not found')
console.log(result.rows[0])
}).catch(error=>{
consol.log(error)
});
});

form in react not submitting to mongoDB ATLAS yet REST client submits

Im building a simple MERN app , in my backend i use REST client to test whether data submits to the database and it works fine , but in my frontend the form handling submission to database does not work data being submitted is a product object with name, image, price and available attributes
backend:
server.js
const express = require('express')
const app = express()
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const userURLS = require('./api/auth')
const multer = require('multer')
const productsURLS = require('./api/products')
dotenv.config()
mongoose.connect(process.env.DB_ACCESS, { useNewUrlParser: true }, () => {
console.log('DB CONNECTED!')
})
app.use(express.json())
app.use('/user', userURLS)
app.use(multer({ dest: "./uploads/" ,
rename: (fieldname, filename) => {
return filename;
}
}).single('photo'));
app.use('/products', productsURLS)
app.listen(7000, ()=> {
console.log('Server is Up & Running!')
})
product.js
const express = require('express')
const router = express.Router()
const fs = require('fs')
const product = require('../models/products');
const { request } = require('http');
const { response } = require('express');
router.post('/add-product', (request,response) => {
var newItem = new product({
name:request.body.name,
img:request.body.img,
price:request.body.price,
available:request.body.available
});
newItem.img.data = fs.readFileSync(request.body.img)
newItem.img.contentType = 'image/png';
newItem.save()
.then((data)=>{
response.json(data)
})
.catch((error)=> {
response.json(error)
})
});
router.get('/', (request, response) => {
product.find()
.then((data)=>{
response.json(data)
})
.catch((error)=> {
response.json(error)
})
})
test.http file used with Rest client
POST http://localhost:7000/products/add-product http/1.1
Content-Type: application/json
{
"name":"dji drone",
"img":"./uploads/dose-media-r6WkZ0gcDa0-unsplash-removebg-preview.png",
"price":"300",
"available":true
}
frontend:
AddProduct.jsx
import React, { Component } from 'react'
import axios from 'axios'
class AddProduct extends Component {
constructor(){
super()
this.state = {
//products:[],
name:'',
img:'',
price:'',
available:''
}
this.changedProductname = this.changedProductname.bind(this)
this.changedProductimg = this.changedProductimg.bind(this)
this.changedProductprice = this.changedProductprice.bind(this)
this.changedProductavail = this.changedProductavail.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
/*
componentDidMount(){
axios.get('http://localhost:7000/products')
.then(response =>{
if (response.data.length > 0) {
this.setState({
products:response.data.map(product => product.name),
name: response.data[0].name
})
}
})
}
*/
changedProductname(event){
this.setState({
name:event.target.value
})
}
changedProductimg(event){
this.setState({
img:event.target.value
})
}
changedProductprice(event){
this.setState({
price:event.target.value
})
}
changedProductavail(event){
this.setState({
available:event.target.value
})
}
onSubmit(event){
event.preventDefault()
const product = {
name: this.state.name,
img: this.state.img,
price: this.state.price,
available: this.state.available
}
console.log(product)
axios.post('http://localhost:7000/products/add-product', product)
.then(response => console.log(response.data))
window.location = '/'
alert("product added successfully")
}
render() {
return (
<div>
<div className="skewed"></div>
<div className='container' style={{ paddingLeft:'300px', marginTop:'160px', marginBottom:'160px' }}>
<div className="card shadow " style={{ width:'520px', height:'600px' , borderRadius:'15px' , border:'none'}}>
<form onSubmit={this.onSubmit} method="post" style={{ width:'380px', textAlign:'', marginLeft:'70px', paddingTop:'90px'}}>
<h3 style={{ paddingBottom:'30px' }}>Add product</h3>
<div className="form-group">
<label htmlFor="name">Name</label>
<input onChange={ this.changedProductname } value={ this.state.name } type="text" className="form-control" id='name'/>
</div>
<div className="form-group">
<label htmlFor="img">Image</label>
<input name='photo' onChange={ this.changedProductimg } value={ this.state.img } type="file" class="form-control-file" id='img'/>
</div>
<div className="form-group">
<label htmlFor="price">Price</label>
<input onChange={ this.changedProductprice } value={ this.state.price } type="text" className="form-control" id='price'/>
</div>
<div className="form-group form-check">
<input onChange={ this.changedProductavail } value={ this.state.available } type="checkbox" class="form-check-input" id="avail"/>
<label class="form-check-label" htmlFor="avail">Available</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
);
}
}
export default AddProduct;

React and node js form image submission

React js front end
const AddPost = ({setAlert}) => {
const [post, setPost] = useState({
name: '',
subject: '',
description: '',
categories: '',
errors: {}
});
const [file, setFile] = useState('');
const [category, setCategory] = useState([]);
useEffect(()=>{
axios.get('/api/categories')
.then((res)=>{
setCategory(res.data);
})
.catch(err => console.error(err))
},[]);
const {name, subject, description,categories} = post;
const onChangeHandler = e =>{
setFile(e.target.files[0]);
};
const onChange = e =>{
setPost({...post, [e.target.name]: e.target.value });
};
const onSubmit = e => {
e.preventDefault();
const formData = new FormData();
formData.append('myImage',file);
const config = {
headers:{'Content-Type': 'multipart/form-data'}
};
const data = {
name: name,
subject: subject,
description: description,
categories: categories,
...formData
};
axios.post('/api/articles/add',data,config)
.then( res => {
console.log('success test', res.data);
setAlert('Article Added','success');
})
.catch((err) => {
console.log('error failed',err);
});
setPost({
name: '',
subject: '',
description: '',
categories: '',
});
setFile({file:''})
};
return (
<Fragment>
<div className="container">
<div className="row justify-content-center">
<div className="col-6">
<h3>Add Posts</h3>
<form onSubmit={e => onSubmit(e)}>
<div className="form-group">
<input
type="text"
name='name'
value={name}
className="form-control"
placeholder="Authors name"
onChange={e => onChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
name='subject'
value={subject}
className="form-control"
placeholder="subject"
onChange={e => onChange(e)}
/>
</div>
<div className="form-group">
<select name='categories'
value={categories}
onChange={e => onChange(e)}
className="form-control">
<option selected>Choose category</option>
{
category.map((item,index)=>(
<option key={index}
>{item.name}
</option>
))
}
</select>
</div>
<div className="form-group">
<textarea
rows="6"
className="form-control"
name='description'
value={description}
placeholder="content"
onChange={e => onChange(e)}> </textarea>
</div>
<input type="file" name='myImage' onChange={e => onChangeHandler(e)} />
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</Fragment>
);
};
This is code for node backend
router.post('/add',(req,res) => {
upload(req,res,(err) => {
if(err){
res.send(err);
}else{
console.log(req.file);
res.send('test');
}
});
var name = req.body.name;
var subject = req.body.subject;
var description = req.body.description;
var categories = req.body.categories;
if(req.file){
var myImage = req.file.filename
}else{
myImage = 'noImage2.jpg'
}
newArticle = new Article({
name: name,
subject: subject,
description: description,
categories: categories,
image: myImage
});
newArticle.save();
try{ res.send('success')}
catch{res.status(400).json('error')}
});`
I have a react blog that contains authors name, title, body and image, I'm using multer in my node server to handle image upload but i don't know how to send both the image and other form data together. I can send them separately. But i need to send them together I've tried formData. Please any help will be appreciated.

Categories

Resources