Path validation error when pushing in react but works in postman/node directly - node.js

I am trying to push info from my sign up page . I can display it and even get an error 500 but i see a path validation even though i can directly post from postman to my db. Here is my signUp page . My model and route is written all the same so i dont understand
import React from "react";
import {
MDBBtn,
MDBContainer,
MDBRow,
MDBCol,
MDBCard,
MDBCardBody,
MDBCardImage,
MDBInput,
MDBIcon,
MDBCheckbox,
} from "mdb-react-ui-kit";
import Navbar from "./Navbar";
import Footer from "./Footer";
import {useState} from "react";
// const initFormData = Object({
// //declaration de l'objet initiale pour recevoir les credentials
// username: "",
// email: "",
// password: "",
// // passwordCheck: "",ls
// });
const SignUpForm = () => {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const collectData = async () => {
console.warn("warn" , username,email,password)
let result = await fetch("http://localhost:8000/api/auth/register",{
method: "post",
body: JSON.stringify({username,email,password}),
headers:{
'Content-type':'shop/JSON'
}
});
result = await result.json();
console.warn(result);
}
return (
<>
<Navbar />
<MDBContainer fluid>
<MDBCard className="text-black m-5" style={{borderRadius: "25px"}}>
<MDBCardBody>
<MDBRow>
<MDBCol
md="10"
lg="6"
className="order-2 order-lg-1 d-flex flex-column align-items-center"
>
<p className="text-center h1 fw-bold mb-5 mx-1 mx-md-4 mt-4">
Sign up
</p>
<div className="d-flex flex-row align-items-center mb-4 ">
<MDBIcon fas icon="user me-3" size="lg" />
<MDBInput
label="Votre Nom"
id="form1"
type="text"
className="w-100"
value={username}
onChange={(e) => setUsername("username", e.target.value)}
/>
</div>
<div className="d-flex flex-row align-items-center mb-4 ">
<MDBIcon fas icon="user me-3" size="lg" />
<MDBInput
label="Email"
id="email"
type="email"
className="w-100"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="d-flex flex-row align-items-center mb-4">
<MDBIcon fas icon="lock me-3" size="lg" />
<MDBInput
label="Mot de passe"
id="form3"
type="password"
name="password"
value={password}
onChange={(e) => setPassword("password" , e.target.value)}
/>
</div>
<div className="mb-4">
<MDBCheckbox
name="flexCheck"
value=""
id="flexCheckDefault"
label="Subscribe to our newsletter"
/>
</div>
<MDBBtn className="mb-4" size="lg" onClick={collectData()}>
Register
</MDBBtn>
</MDBCol>
<MDBCol
md="10"
lg="6"
className="order-1 order-lg-2 d-flex align-items-center"
>
<MDBCardImage
src="https://mdbcdn.b-cdn.net/img/Photos/new-templates/bootstrap-registration/draw1.webp"
fluid
/>
</MDBCol>
</MDBRow>
</MDBCardBody>
</MDBCard>
</MDBContainer>
<Footer />
</>
);
};
export default SignUpForm;
i expected to be able to push but i get

Related

Cannot access 'useState' before initialization in react.js

In react.js I am adding a form with some parameter.
import React , {useState} from "react";
AddUser component has some parameter in which I have to store data.
const AddUser = () => {
const [user, useState] = useState({
name: " ",
username: " ",
email: " ",
phone: " ",
website: " "
});
This code is used for initializing the parameter of useState.
const {name,username,email,phone,website} = user;
const onInputChange = e => {
console.log(e.target.value)
}
return (
<div className="container mt-5">
<div className="w-75 mx-auto shadow p-5">
<h2 className="text-center mb-4">Add User</h2>
This is the form where I submit some data of parameters.
<form>
<div class="form-group mb-4">
<input type="text" value={name} name="name" onChange={e => onInputChange(e)} class="form-control" aria-describedby="emailHelp" placeholder="Enter Name" />
</div>
<div class="form-group mb-4">
<input type="text" value={username} name="username" onChange={e => onInputChange(e)} class="form-control" placeholder="Enter Username" />
</div>
<div class="form-group mb-4">
<input type="email" value={email} name="email" onChange={e => onInputChange(e)} class="form-control" aria-describedby="emailHelp" placeholder="Enter email" />
</div>
<div class="form-group mb-4">
<input type="text" value={phone} name="phone" onChange={e => onInputChange(e)} class="form-control" placeholder="Enter Contact" />
</div>
<div class="form-group mb-4">
<input type="text" value={website} name="website" onChange={e => onInputChange(e)} class="form-control" placeholder="Enter Website" />
</div>
<button type="submit" class="btn btn-primary">Add User</button>
</form>
</div>
</div>
)
}
export default AddUser;
Error:
Uncaught ReferenceError: Cannot access 'useState' before initialization
at AddUser (AddUser.js:4:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at beginWork$1 (react-dom.development.js:27426:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
at renderRootSync (react-dom.development.js:26434:1)
at recoverFromConcurrentError (react-dom.development.js:25850:1)
at performConcurrentWorkOnRoot (react-dom.development.js:25750:1)
useState is a react hook, you cannot use its name to name a variable or function. Change your AddUser code shown on this page to this:
const AddUser = () => {
const [user, setUser] = useState({
name: " ",
username: " ",
email: " ",
phone: " ",
website: " "
});

TypeError: Cannot read properties of undefined (reading 'id') - React App

I've trying to edit an entry of the data fetched from mysql and want to reflect if back in mysql db. For this im using post method of Axios. But im getting the following error when i try to edit the data and see for changes.
TypeError: Cannot read properties of undefined (reading 'id')
at C:\Users\Rahul01\Desktop\DBMS-PROJECT\BusTicketManagementSystem\server\index.js:123:23
at Layer.handle [as handle_request] (C:\Users\Rahul01\Desktop\DBMS-PROJECT\BusTicketManagementSystem\server\node_modules\express\lib\router\layer.js:95:5)
Here are the Codes
1.index.js
app.post('/admin/updatebus',(res,req)=>{
const id=req.body.id
const name=req.body.newbusname
const fromcity=req.body.newfromstation
const tocity=req.body.newtostation
const capacity=req.body.newcapacity+1
db.query("UPDATE bus SET busname=?,fromcity=?,tocity=?,capacity=? WHERE busid=? ",[name,fromcity,tocity,capacity,id+1],(err,result)=>{
if(err)
{
console.log(err);
res.send({op:f})
}
else
{
res.send({op:s});
}
})
})
2.Editbus.js
import Axios from 'axios'
import React, { useState } from 'react'
import { useParams } from 'react-router-dom'
export default function Editbus() {
const [newbusname, setnewbusname] = useState('')
const [newfromstation, setnewfromstation] = useState('')
const [newtostation, setnewtostation] = useState('')
const [newcapacity, setnewcapacity] = useState(0)
const {id}=useParams();
const handlesave=(e)=>{
// alert(key)
alert('Name'+newbusname+"\n From:"+newfromstation+"\nTo: "+newtostation+"\n Capacity: "+newcapacity)
Axios.post('http://localhost:3001/admin/updatebus',{
newbusname:newbusname,
newfromstation:newfromstation,
newtostation:newtostation,
newcapacity:newcapacity,
id:parseInt(id)
}).then((resp)=>{
if(resp.data.op==='s')
{
alert('Updated')
}
else
{
alert('Not Updated')
}
})
e.preventDefault()
}
return (
<>
<div class="container-contact100">
<div class="wrap-contact100">
<form class="contact100-form validate-form">
<span class="contact100-form-title">
Edit Bus {id}
</span>
<div class="wrap-input100 validate-input" data-validate="Name is required">
<input class="input100" type="text" name="name" onChange={e=>setnewbusname(e.target.value)} placeholder="New Bus Name" required/>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Valid email is required: ex#abc.xyz">
<input class="input100" type="text" name="email" onChange={e=>setnewfromstation(e.target.value)} placeholder="From Bus Stop" required/>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Valid email is required: ex#abc.xyz">
<input class="input100" type="text" name="email" onChange={e=>setnewtostation(e.target.value)} placeholder="To Bus Stop" required/>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Valid email is required: ex#abc.xyz">
<input class="input100" type="number" name="email" onChange={e=>setnewcapacity(e.target.value)} placeholder="New Capacity" required/>
<span class="focus-input100"></span>
</div>
<button onClick={handlesave}>Update</button>
</form>
</div>
</div>
<div id="dropDownSelect1"></div>
</>
)
}
In App.js
<Route exact path="/admin/editbus/:id" element={}>
It should be (req, res) instead of (res,req) in the .post handler.
Corrected Code:
app.post('/admin/updatebus',(req,res)=>{}
First Parameter should be for Request and second one for the Response.
Tip:
Include type='button' in the Submit Button so that the HTML form doesn't gets submitted.
<button type="button" onClick={handlesave}>Update</button>

Trying to display IMG with src set to Binary/Buffer image data from Mongoose

Trying to display IMGs with React/JSX with Buffered/Binary data saved to my MongoDB/Mongoose database.
i iterate over the data array with the IMG element looking like this:
<img src={`data:${item.img.contentType};base64,${item.img.data.data.toString("base64")}`} alt="" />
import React, { useState, useEffect } from "react";
import axios from "axios";
const FilesUpload = () => {
const [allPics, setAllPics] = useState([]);
useEffect(() => {
const getPics = async () => {
let res = await axios.get("http://localhost:8080/");
setAllPics(res.data);
};
// query the server for all of the picture objects
getPics();
}, []);
const [state, setState] = useState({});
const handleChange = (e) => {
e.preventDefault();
setState(e.target.value);
console.log(state);
};
return (
<>
<h1>upload an image</h1>
<hr />
<div>
<form
action="http://localhost:8080/"
method="POST"
encType="multipart/form-data"
>
<div>
<label>Image Title</label>
<input type="text" id="name" placeholder="Name" name="name" onChange={handleChange} value={state.name}/>
</div>
<div>
<label htmlFor="desc">Image Description</label>
<textarea id="desc" name="desc" rows="2" placeholder="Description"
onChange={handleChange} value={state.desc}/>
</div>
<div>
<label htmlFor="image">Upload Image</label>
<input type="file" id="image" name="image" required />
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
</div>
{allPics.length > 0 ? (
<div>
{allPics.map((item, index) => (
<div key={index}>
<div>
<img src={`data:${item.img.contentType};base64,${item.img.data.data.toString("base64")}`} alt="" />
</div>
</div>
))}
</div>
) : (
<>
<hr />
<br />
<h1>uploaded files</h1>
<h5>Loading..</h5>
</>
)}
</>
);
};
export default FilesUpload;
but I always get ERR_INVALID_URL:
from similar threads on the net I've read that I need to take those comma-delimitated values and remove the comma which will give me the proper data. having a hard time figuring that out. any help would be great. thanks
I was facing the same problem after saving image like this in my mongoose model and after many research I resolved this, hope this works for you also
const base64String = btoa(String.fromCharCode(...new Uint8Array(item.img.data.data)));
and in img tag put this -:
src={`data:image/${item?.img?.contentType};base64,${base64String}`}

can't upload images using react to backend using axios and nodejs

I try to upload a photo from React and save it in a public folder on the backend and then display the filename in the MySql database
After trying it through Postman, the photo has been successfully uploaded and appears and produces a json like this
{"image":"/img/14d714a9ed97fb92db657b9518e89a1e.png",
"id_produk":23,
"id_user":19,
"Nama_toko":"Nihongo Mantappu",
"Nama_Produk":"Butter",
"Deskripsi":"Mentega Blueband 50g",
"Price":5000,
"Jumlah_stock":7},
but when I tried it in React it only produced this
{"image":"/img/",
"id_produk":29,
"id_user":19,
"Nama_toko":"Nihongo Mantappu",
"Nama_Produk":"Beras Cinajur",
"Deskripsi":"Beras Cianjur 1kg",
"Price":500000,"Jumlah_stock":20}
so that when i check the database on the image it becomes empty
here the code for upload image
import React from 'react'
import jwt_decode from 'jwt-decode';
import 'bootstrap/dist/css/bootstrap.min.css';
import NavbarPenjual from '../../Component/NavbarPenjual';
import {addproduk} from '../../View/UserFunctions';
import { Form,Col, Button } from 'react-bootstrap';
class TambahProduk extends React.Component{
constructor(){
super()
this.state={
id_user:'',
Nama_toko:'',
Nama_produk: '',
Harga:'',
image: '',
Deskripsi: '',
Jumlah_produk: '',
error:{}
}
this.onChange=this.onChange.bind(this)
this.onSubmit=this.onSubmit.bind(this)
}
onChange(e){
this.setState({[e.target.name]:e.target.value})
}
componentDidMount(){
const token = localStorage.getItem('usertoken')
const decoded= token ? jwt_decode(token) : null;
this.setState({
id_user:decoded.id_user,
Nama_toko:decoded.Nama_toko
})
}
onSubmit(e){
e.preventDefault()
const newProduk={
id_user:this.state.id_user,
Nama_toko:this.state.Nama_toko,
Nama_Produk: this.state.Nama_Produk,
Price:this.state.Price,
image: this.state.image,
Deskripsi: this.state.Deskripsi,
Jumlah_stock: this.state.Jumlah_stock,
}
console.log(newProduk)
addproduk(newProduk).then(res =>{
//localStorage.setItem('usertoken',res.data.token);
this.props.history.push(`/DashboardPenjual`)
}).catch(err=>{
console.log(err)
alert("gagal")
})
}
render(){
return(
<div>
<NavbarPenjual/>
<Form className="container"style={{marginTop:28}} noValidate onSubmit={this.onSubmit}>
<h2>Tambah Produk</h2>
<Form.Row controlId="exampleForm.ControlInput1">
<Form.Label column lg={2}>
Nama Produk
</Form.Label>
<br/>
<Col>
<Form.Control
type="text"
placeholder="Masukan Nama Produk"
name="Nama_Produk"
value={this.state.Nama_Produk}
onChange={this.onChange}
/>
</Col>
</Form.Row>
<br/>
<Form.Row controlId="exampleForm.ControlInput1">
<Form.Label column lg={2}>
Harga Produk
</Form.Label>
<br/>
<Col>
<Form.Control type="text"
placeholder="Masukan Harga Produk"
name="Price"
value={this.state.Price}
onChange={this.onChange}
/>
</Col>
</Form.Row>
<br/>
<Form.Row controlId="exampleForm.ControlInput1">
<Form.Label column lg={2}>
Jumlah Produk
</Form.Label>
<br/>
<Col>
<Form.Control
type="text"
placeholder="Masukan Jumlah Produk"
name="Jumlah_stock"
value={this.state.Jumlah_stock}
onChange={this.onChange}
/>
</Col>
</Form.Row>
<br/>
<Form.Row controlId="exampleForm.ControlInput1">
<Col>
<Form.Group controlId="exampleForm.ControlTextarea1">
<Form.Label>Deskripsi Produk</Form.Label>
<br/>
<Form.Control
as="textarea"
rows="3"
name="Deskripsi"
value={this.state.Deskripsi}
onChange={this.onChange}
/>
</Form.Group>
</Col>
</Form.Row>
<br/>
<Form.Row controlId="exampleForm.ControlInput1">
<Form.Group>
<Form.File
id="exampleFormControlFile1"
label="Masukan Foto Produk"
type="image"
name="image"
value={this.state.image}
onChange={this.onChange}
/>
</Form.Group>
</Form.Row>
<br/>
<button
type="submit"
className="btn btn-lg btn-primary btn-block"
>Submit</button>
<Form.Row controlId="exampleForm.ControlInput1" style={{ visibility: "hidden" }}>
<Col>
<Form.Group controlId="exampleForm.ControlInput1">
<br/>
<Form.Control
as="text"
name="id_user"
value={this.state.id_user}
onChange={this.onChange}
/>
</Form.Group>
</Col>
</Form.Row>
<Form.Row controlId="exampleForm.ControlInput1" style={{ visibility: "hidden" }}>
<Col>
<Form.Group controlId="exampleForm.ControlTextarea1">
<br/>
<Form.Control disabled
as="area"
name="Nama_toko"
value={this.state.Nama_toko}
onChange={this.onChange}
/>
</Form.Group>
</Col>
</Form.Row>
</Form>
</div>
)
}
}
export default TambahProduk;
this is part of the axios userfuction for add product
export const addproduk = newProduk =>{
return axios
.post('product/addproduk',{
id_user:newProduk.id_user,
Nama_toko:newProduk.Nama_toko,
Nama_Produk:newProduk.Nama_Produk,
image: newProduk.image,
Deskripsi:newProduk.Deskripsi,
Price:newProduk.Price,
Jumlah_stock:newProduk.Jumlah_stock
})
.then(res=>{
console.log("produk di tambahkan")
return res
})
.catch(err=>{
console.log(err);
return err;
})
}
How do I get uploaded like when I use Postman?
Image is not an value, it's a file. So, in the onChange function you assigned the image.target.name as value
Try like this :
event.target.name === "image"? event.target.files[0] : event.target.value;

How to create onSubmit with Material-UI

So I'm fairly new to node.js / react / material-ui. I've been following a guide to try setting up a website and have been getting on pretty well. I decided to include material-ui for snazzy components (not part of the guide) and then got stuck because I can't seem to fire custom functions whilst using a themed ui.
With the below code, I can create everything fine if I ditch the 'classes' props. I can add my function and everything works. But I obviously lose all my styling if I do this.
const styles = theme => ({
// Styling - omitted
});
const Login = (props) => {
const {classes} = props;
return(
<div>
<Paper className={classes.root}>
<form className={classes.container} noValidate autoComplete="off">
<TextField
id="email"
label="Email"
className={classes.textField}
InputProps={{
className: classes.input
}}
type="email"
name="email"
autoComplete="email"
margin="normal"
variant="outlined"
required
autoFocus
/>
<TextField
id="outlined"
label="Password"
className={classes.textField}
InputProps={{
className: classes.input
}}
type="password"
autoComplete="current-password"
margin="normal"
variant="outlined"
required
/>
<Typography className={classes.divider} />
<Button
type="submit"
variant="contained"
color="inherit"
className={classes.button}
>
Login
</Button>
</form>
</Paper>
</div>
);
}
Login.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(Login);
I'm trying to combine the styling as well as being able to fire a custom function to submit the form data. Does anyone have any thoughts?
The class property/ styles shouldn't have any effect on form submission custom function. If you think that ditching the 'class props' you can get a custom function to work - post your code so we can help you further. [Your code is missing submit function]
Here is one way to add custom submit function
const Login = (props) => {
const {classes} = props;
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
function handleSubmit(event) {
event.preventDefault();
console.log( 'Email:', email, 'Password: ', password);
// You should see email and password in console.
// ..code to submit form to backend here...
}
return( <div >
<Paper className={classes.root}>
<form className={classes.container} onSubmit={handleSubmit} >
<TextField
....
value={email}
onInput={ e=>setEmail(e.target.value)}
.....
/>
<TextField
....
value={password}
onInput={ e=>setPassword(e.target.value)}
....
/>
<Typography className={classes.divider} />
<Button
type="submit"
....
className={classes.button}
>
Login
</Button>
</form>
</Paper>
</div>
);

Resources