POST http://localhost:7500/api/users/posts 400 (Bad Request) - javascript

So I am trying to save some data into a mongodb data base using axios
I created a form to fill then when i click on save the data must be saved.
this is my try:
import auction1 from '../../Images/auction1.png'
import {useState} from 'react';
import './HomeScreen.css'
import {Button, Modal } from 'react-bootstrap';
import axios from 'axios';
const HomeScreen = ()=>{
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const [name, setName] = useState("");
const [price, setPrice] = useState(null);
const [deadline, setDeadLine] = useState("");
const [description, setDescription] = useState("");
const [img, setImg] = useState("");
const [imgMessage, setImgMessage] = useState(null);
const [error, setError] = useState(false);
const handleSubmit = async(e)=>{
e.preventDefault();
try{
const config = {
headers: {
"Content-Type": "application/json",
}
}
const {data} = await axios.post("http://localhost:7500/api/users/posts",
{name, img, deadline, price, description},
config
);
console.log(data);
}catch(error){
console.log(error.response.data.message);
}
};
const postDetails = (pic)=>{
if(!pic){
return setImgMessage('Please select a picture');
}
setImgMessage(null);
if(pic.type === 'images/jpeg' || pic.type==='image/png'){
const data = new FormData();
data.append('file', pic);
data.append('upload_preset', 'battta');
data.append('cloud_name', 'ChkounZed');
fetch("https://api.cloudinary.com/v1_1/ChkounZed/upload", {
method: 'post',
body: data
})
.then((res)=> res.json())
.then((data)=> {
console.log(data);
setImg(data.url.toString())
})
.catch((error)=>{
console.log(error);
});
}else{
return setImgMessage('Please select a picture');
}
};
return(
<div className="container bg">
<img src ={auction1} className='landing-image' />
<div style={{marginLeft:460}}>
<Button variant="primary" onClick={handleShow}>
Create Post
</Button>
</div>
<Modal show={show} onHide={handleClose}>
<form onSubmit={handleSubmit}>
<Modal.Header closeButton>
<Modal.Title>Create Post</Modal.Title>
</Modal.Header>
<Modal.Body>
<form >
<div className="form-group">
<label>Post Name:</label>
<input type="text" className="form-control" placeholder="Enter Name"
value={name} onChange={(e)=> setName(e.target.value)}/>
</div>
<div className="form-group">
<label>Post Images:</label>
<input type="file" className="form-control" multiple onChange="readURL(this)" accept="Image/*"
onChange={(e)=> postDetails(e.target.files[0])}/>
</div>
<div>
<label>Price:</label>
<input type="number" className="form-control" placeholder="TND"
value={price} onChange={(e)=> setPrice(e.target.value)}/>
</div>
<div>
<label>DeadLine:</label>
<input type="datetime-local" className="form-control"
value={deadline} onChange={(e)=> setDeadLine(e.target.value)}/>
</div>
<div>
<label>Description:</label>
<textarea className="form-control" rows="3"
value={description} onChange={(e)=> setDescription(e.target.value)}/>
</div>
</form>
</Modal.Body>
<Modal.Footer>
<button type="submit" className="btn btn-primary" data-bs-dismiss="modal" onClick={handleClose} >
Save Post
</button>
<button type="submit" className="btn btn-secondary" data-bs-dismiss="modal" onClick={handleClose}>
Close
</button>
</Modal.Footer>
</form>
</Modal>
</div>
)
};
export default HomeScreen;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
that was my react component and the problem is that i keep getting a message that says the post already exists.
this is my postController from the backend side:
const Post = require("../Models/postModel");
const asyncHandler = require("express-async-handler");
const savePost = asyncHandler(async(req,res)=>{
const {name, deadline, price, description, image} = req.body;
const postExists = await Post.findOne({image});
if(postExists){
res.status(400);
throw new Error('Post Already Exists');
}
const post = await Post.create({
name,
deadline,
price,
description,
image
});
if(post){
res.status(201).json({
_id: post._id,
name: post.name,
price: post.price,
image: post.image,
deadline: post.deadline,
description: post.description
});
}else{
res.status(400);
throw new Error('Error');
}
});
module.exports = {savePost};
I would be so grateful if you can give me hand of this and by the way i wanna make my post unique using the images and still did not know how

Can you provide more information? Your Post Model. What happens at the DB Collection? Is it empty?
The response of mongodb includes _id why not use findById instead of find({image}).
When u wipe your database and post the first time whats the response of your post to /api/users/posts?
To make some fields unique for the collection you can use unique like below:
const PlayerSchema = new mongoose.Schema({
name:{
type: String,
unique: true
}
})

Related

POST http://localhost:3000/api/v1/register 500 (Internal Server Error)

When Cloudinary is not included my Code runs fine on Postman. As I include Cloudinary to in register route to add photos to account, I am getting this error
userAction.jsx
export const register = (userData) => async (dispatch) => {
try {
dispatch({ type: REGISTER_USER_REQUEST });
const config = { headers: { "Content-Type": "multipart/form-data" } };
const { data } = await axios.post(`/api/v1/register`, userData, config);
dispatch({ type: REGISTER_USER_SUCCESS, payload: data.user });
} catch (error) {
dispatch({
type: REGISTER_USER_FAIL,
payload: error.response.data.message,
});
}
};
LoginSignup.jsx
import React, {Fragment,useRef,useState, useEffect} from "react";
import "./LoginSignUp.css";
import Loader from "../layout/Loader/Loader";
import { Link, useNavigate } from "react-router-dom";
import LockOpenIcon from '#mui/icons-material/LockOpen';
import EmailIcon from '#mui/icons-material/Email';
import PersonIcon from '#mui/icons-material/Person';
import img from "../../images/Profile.png";
import {useSelector, useDispatch} from "react-redux";
import {clearErrors, login , register} from "../../actions/userAction.jsx";
import {useAlert} from "react-alert";
export default function LoginSignUp(){
const dispatch = useDispatch();
const alert = useAlert();
const navigate = useNavigate();
const {error,loading,isAuthenticated} = useSelector((state)=>state.user);
const loginTab=useRef(null);
const registerTab = useRef(null);
const switcherTab = useRef(null);
const [loginEmail,setLoginEmail] = useState("");
const [loginPassword,setLoginPassword] = useState("");
const [user,setUser] = useState({
name:"",
email:"",
password:"",
});
const {name,email,password} = user;
const [avatar, setAvatar] = useState(img);
const [avatarPreview, setAvatarPreview] = useState(img);
function loginSubmit(e){
e.preventDefault();
dispatch((login(loginEmail,loginPassword)));
}
function registerSubmit(e){
e.preventDefault();
const myForm = new FormData();
myForm.set("name",name);
myForm.set("email",email);
myForm.set("password",password);
myForm.set("avatar",avatar);
dispatch(register(myForm));
}
function registerDataChange(e){
if(e.target.name==="avatar"){
const reader = new FileReader();
reader.onload = ()=>{
if(reader.readyState===2){
setAvatarPreview(reader.result);
setAvatar(reader.result);
}
};
reader.readAsDataURL(e.target.files[0]);
} else {
setUser({...user, [e.target.name]:e.target.value});
}
}
useEffect(()=>{
if(error){
alert.error(error);
dispatch(clearErrors());
}
if(isAuthenticated){
navigate(`/account`);
}
},[dispatch,error,alert,isAuthenticated,navigate]);
const switchTabs = (e, tab) => {
if (tab === "login") {
switcherTab.current.classList.add("shiftToNeutral");
switcherTab.current.classList.remove("shiftToRight");
registerTab.current.classList.remove("shiftToNeutralForm");
loginTab.current.classList.remove("shiftToLeft");
}
if (tab === "register") {
switcherTab.current.classList.add("shiftToRight");
switcherTab.current.classList.remove("shiftToNeutral");
registerTab.current.classList.add("shiftToNeutralForm");
loginTab.current.classList.add("shiftToLeft");
}
};
return(
<Fragment>
{loading ? <Loader/> : (
<Fragment>
<div className="LoginSignUpContainer">
<div className="LoginSignUpBox">
<div>
<div className="login_signUp_toggle">
<p onClick={(e)=>switchTabs(e,"login")}>Login</p>
<p onClick={(e)=>switchTabs(e,"register")}>Register</p>
</div>
<button ref={switcherTab}></button>
</div>
<form
className="signUpForm"
ref={registerTab}
encType="multipart/form-data"
onSubmit={registerSubmit}
>
<div className="signUpName">
<PersonIcon />
<input
type="text"
placeholder="Name"
required
name="name"
value={name}
onChange={registerDataChange}
/>
</div>
<div className="signUpEmail">
<EmailIcon />
<input
type="email"
placeholder="Email"
required
name="email"
value={email}
onChange={registerDataChange}
/>
</div>
<div className="signUpPassword">
<LockOpenIcon />
<input
type="password"
placeholder="Password"
required
name="password"
value={password}
onChange={registerDataChange}
/>
</div>
<div id="registerImage">
<img src={avatarPreview} alt="Avatar Preview" />
<input
type="file"
name="avatar"
accept="image/*"
onChange={registerDataChange}
/>
</div>
<input type="submit" value="Register" className="signUpBtn" />
</form>
</div>
</div>
</Fragment>
)}
</Fragment>
);
}
userController.jsx
exports.RegisterUser = catchAsyncErrors( async (req,res,next)=>{
// const myCloud = await cloudinary.v2.uploader.upload(req.body.avatar,{
// folder: "avatars",
// width: 150,
// crop:"scale",
// });
const {name,email,password} = req.body;
const user = await User.create({
name,
email,
password,
avatar: {
public_id:"myCloud.public_id",
url: "myCloud.secure_url",
}
});
sendToken(user,201,res);
});
I have an id on Cloudinary and imported its Name, API_KEY, API_SECRET
Backend code works well on postman without Cloudinary
In Postman you are not adding image. But in client side login form, you are adding image alongside other data.
In backend you are getting email, name, password from req.body.But image data will be available in req.file.
As an example
if (req.file) {
const avatar= req.file.originalName;
req.body = { ...req.body, avatar};
}
await Model.create(req.body);

react js and node Can't see img of new user

When I try to register a new user all data are passed except "avatar", even if that avatar is regularly uploaded on my Cloudinary.
Don't even know what is the problem in and tried to find answer on google but unsuccessfully, so any help is very welcome :D
Here is some code, if need more tell me in a comment and I'll send you
Cannot finish my site, don't know what to do...
// frontend Register component
import React, { Fragment, useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import MetaData from '../layout/MetaData';
import { useAlert } from 'react-alert';
import { useDispatch, useSelector } from 'react-redux';
import { register, clearErrors } from '../../actions/userActions';
const Register = () => {
const navigate = useNavigate();
const [user, setUser] = useState({
name: '',
email: '',
password: '',
});
const { name, email, password } = user;
const [avatar, setAvatar] = useState('');
const [avatarPreview, setAvatarPreview] = useState(
'/images/default_avatar.jpg'
);
const alert = useAlert();
const dispatch = useDispatch();
const { isAuthenticated, error, loading } = useSelector(
(state) => state.auth
);
useEffect(() => {
if (isAuthenticated) {
navigate('/');
}
if (error) {
alert.error(error);
dispatch(clearErrors());
}
}, [dispatch, alert, isAuthenticated, error, navigate]);
const submitHandler = (e) => {
e.preventDefault();
const formData = new FormData();
formData.set('name', name);
formData.set('email', email);
formData.set('password', password);
formData.set('avatar', avatar);
dispatch(register(formData));
};
const onChange = (e) => {
if (e.target.name === 'avatar') {
const reader = new FileReader();
reader.onload = () => {
if (reader.readyState === 2) {
setAvatarPreview(reader.result);
setAvatar(reader.result);
}
};
reader.readAsDataURL(e.target.files[0]);
} else {
setUser({ ...user, [e.target.name]: e.target.value });
}
};
return (
<Fragment>
<MetaData title={'Register User'} />
<div className='row wrapper'>
<div className='col-10 col-lg-5'>
<form
className='shadow-lg'
onSubmit={submitHandler}
encType='multipart/form-data'
>
<h1 className='mb-3'>Register</h1>
<div className='form-group'>
<label htmlFor='email_field'>Name</label>
<input
type='name'
id='name_field'
className='form-control'
name='name'
value={name}
onChange={onChange}
/>
</div>
<div className='form-group'>
<label htmlFor='email_field'>Email</label>
<input
type='email'
id='email_field'
className='form-control'
name='email'
value={email}
onChange={onChange}
/>
</div>
<div className='form-group'>
<label htmlFor='password_field'>Password</label>
<input
type='password'
id='password_field'
className='form-control'
name='password'
value={password}
onChange={onChange}
/>
</div>
<div className='form-group'>
<label htmlFor='avatar_upload'>Avatar</label>
<div className='d-flex align-items-center'>
<div>
<figure className='avatar mr-3 item-rtl'>
<img
src={avatarPreview}
className='rounded-circle'
alt='Avatar Preview'
/>
</figure>
</div>
<div className='custom-file'>
<input
type='file'
name='avatar'
className='custom-file-input'
id='customFile'
accept='iamges/*'
onChange={onChange}
/>
<label className='custom-file-label' htmlFor='customFile'>
Choose Avatar
</label>
</div>
</div>
</div>
<button
id='register_button'
type='submit'
className='btn btn-block py-3'
disabled={loading ? true : false}
>
REGISTER
</button>
</form>
</div>
</div>
</Fragment>
);
};
export default Register;
// backend Register a user => /api/v1/register
exports.registerUser = catchAsyncErrors(async (req, res, next) => {
const result = await cloudinary.v2.uploader.upload(req.body.avatar, {
folder: 'avatars',
width: 150,
crop: 'scale',
});
const { name, email, password } = req.body;
const user = await User.create({
name,
email,
password,
avatar: {
public_id: result.public_id,
url: result.secure_url,
},
});
sendToken(user, 200, res);
});

Update List of users Table after POST fetch request

Good afternoon everyone. I have 2 pages: one responsible for displaying List of Users in the table (data comes from fetching), then on Add User button click opens a Modal window with Sign Up form. On submitting this form, data about a new user is sent to an api (fetch POST), then sign up form closes and then the List of Users table is supposed to be updated with a newly added user. I fail to figure out how to correctly perform this update. Simple getUser() call in handleUserFormSubmit function doesn't do the trick (table is not re-rendered). Thanks in advance for any help
// Sign-Up Form Component
import React, { useState, useEffect } from "react";
const SignUpForm = ({
isFormVisible,
setIsFormVisible,
userList,
getUsers,
}) => {
const [usernameList, setUsernameList] = useState([]);
const [username, setUsername] = useState("");
const [usertype, setUsertype] = useState("");
const [password, setPassword] = useState("");
const [verifyPassword, setVerifyPassword] = useState("");
const [isChecked, setIsChecked] = useState(true);
const getUsernameList = () =>
userList.forEach(({ username }) => usernameList.push(username));
useEffect(() => {
getUsernameList();
console.log(usernameList);
}, []);
const addNewUser = async () => {
try {
const response = await fetch(
"http://www.someapi.com/add",
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
username,
usertype,
password,
}),
}
);
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error.message);
}
};
const handleUserFormSubmit = (e) => {
e.preventDefault();
addNewUser();
setIsFormVisible(false);
getUsers();
}
};
return (
<>
{isFormVisible && (
<div
className={`${
isFormVisible ? "modal-overlay show-modal" : "modal-overlay"
}`}
>
<div className="sign-up-container">
<div className="sign-up-header-container">
<h2>Sign Up</h2>
<p>Please fill in this form to create an acoount</p>
</div>
<form className="form" onSubmit={(e) => e.preventDefault()}>
<label htmlFor="username">Username</label>{" "}
<br />
<input
type="text"
placeholder="Enter username"
id="username"
name="username"
value={username}
required
onChange={(e) => {
setUsername(e.target.value.toLowerCase());
setIsNameProvided(true);
}}
/>
<br />
<label htmlFor="usertype">User type</label>{" "}
<br />
<select
name="usertype"
id="usertype-select"
required
onChange={(e) => {
setUsertype(e.target.value);
setIsTypeSelected(true);
}}
>
<option value=""></option>
<option value="instructor">instructor</option>
<option value="maintenance">maintenance</option>
</select>
<br />
<label htmlFor="password">Password</label>{" "}
<br />
<input
type="password"
placeholder="Enter password"
id="password"
name="password"
required
value={password}
onCopy={(e) => e.preventDefault()}
onPaste={(e) => e.preventDefault()}
onChange={(e) => {
setPassword(e.target.value);
setIsPasswordProvided(true);
}}
/>
<br />
<label htmlFor="rpassword">Repeat Password</label>{" "}
<br />
<input
type="password"
placeholder="Repeat"
id="rpassword"
name="rpassword"
required
value={verifyPassword}
onCopy={(e) => e.preventDefault()}
onPaste={(e) => e.preventDefault()}
onChange={(e) => {
setVerifyPassword(e.target.value);
setIsConfirmPasswordProvided(true);
}}
/>{" "}
<br />
<input
type="checkbox"
id="remember"
name="remember"
checked={isChecked}
onChange={() => setIsChecked(!isChecked)}
/>
<label htmlFor="remember">Remember me</label>
<p className="terms-privacy">
By creating an account you agree to our{" "}
Terms & Privacy
</p>
<div className="btn-container">
<button
type="button"
className="cancel-btn"
onClick={() => setIsFormVisible(false)}
>
CANCEL
</button>
<button
type="submit"
className="sign-up-btn"
onClick={(e) => handleUserFormSubmit(e)}
>
SIGN UP
</button>
</div>
</form>
</div>
</div>
)}
</>
);
};
export default SignUpForm;
// List Of Users Component:
import React, { useState, useEffect } from "react";
import Loading from "./Loading";
import SignUpForm from "./SignUpForm";
import "./User.css";
const User = () => {
const [userList, setUserList] = useState([]);
const [loading, setLoading] = useState(true);
const [isFormVisible, setIsFormVisible] = useState(false);
const getUsers = async () => {
setLoading(true);
try {
const response = await fetch(
"http://www.someapi.com"
);
const data = await response.json();
setUserList(data);
setLoading(false);
} catch (error) {
console.error(error.message);
setLoading(false);
}
};
useEffect(() => {
getUsers();
}, []);
if (loading) return <Loading />;
return (
<section className="section-user">
<h1>List of Users</h1>
<div className="users-table-container">
<table className="users-table">
<thead>
<tr>
<th>Username</th>
<th>User type</th>
</tr>
</thead>
<tbody>
{userList.map(({ username, userType, hashedPswd }) => (
<tr key={hashedPswd}>
<td>{username}</td>
<td>{userType}</td>
</tr>
))}
</tbody>
</table>
</div>
<button className="add-user-btn" onClick={() => setIsFormVisible(true)}>
Add User
</button>
{isFormVisible && (
<SignUpForm
isFormVisible={isFormVisible}
setIsFormVisible={setIsFormVisible}
userList={userList}
getUsers={getUsers}
/>
)}
</section>
);
};
export default User;
You are directly manipulating a state rather than using setState. In this case react does not re-render the page even if you manipulate the state. So:
// wrong
const getUsernameList = () =>
userList.forEach(({ username }) => usernameList.push(username));
// correct
const getUsernameList = () => {
const list = userList.map(user => user.username)
setUsernameList(list)
}
*Edit: I think you are not saving your response data after creating a new user
In User component add
useEffect(() => {
if (isFormVisible) getUsers();
}, [isFormVisible]);

How to upload a file to MySQL database using Nodejs backend and display the photo

I am trying to upload a photo to mySQL database using a node backend but for some reason I am getting that what I have uploaded is undefined.
I have declared a new variable "Photo2" which is storing that photo and I console.log it but I get "undefined" in my console
The form:
import axios from "axios";
import { React, useState, useEffect } from "react";
import { useHistory, withRouter } from "react-router-dom";
function UserMaster_Edit(props) {
const [CmpnyCode, setCmpnyCode] = useState("");
const [UserID, setUserID] = useState("");
const [UserFullName, setUserFullName] = useState("");
const [UserDetail, setUserDetail] = useState("");
const [LoginID, setLoginID] = useState("");
const [Password, setPassword] = useState("");
const [UserPin, setUserPin] = useState("");
const [UserEmailID, setUserEmailID] = useState("");
const [UserFP, setUserFP] = useState("");
const [Photo, setPhoto] = useState("");
const [IsActive, setIsActive] = useState("");
const [LicCount, setLicCount] = useState("");
const [DateCreated, setDateCreated] = useState("");
const [CreatedBy, setCreatedBy] = useState("");
const [RecordChanged, setRecordChanged] = useState("");
const [LocationID, setLocationID] = useState("");
const [isValid, setisValid] = useState("");
const [isDeleted, setisDeleted] = useState("");
const history = useHistory();
const argu = props.match.params.UserID;
useEffect(() => {
axios.get("http://localhost:8000/getuserid/" + argu).then((response) => {
setCmpnyCode(response.data[0].CmpnyCode);
setUserID(response.data[0].UserID);
setUserFullName(response.data[0].UserFullName);
setUserDetail(response.data[0].UserDetail);
setLoginID(response.data[0].LoginID);
setPassword(response.data[0].Password);
setUserPin(response.data[0].UserPin);
setUserEmailID(response.data[0].UserEmailID);
setUserFP(response.data[0].UserFP);
setPhoto(response.data[0].Photo);
setIsActive(response.data[0].IsActive.data[0]);
setLicCount(response.data[0].LicCount);
setDateCreated(response.data[0].DateCreated);
setCreatedBy(response.data[0].CreatedBy);
setRecordChanged(response.data[0].RecordChanged.data[0]);
setLocationID(response.data[0].LocationID);
setisValid(response.data[0].isValid);
setisDeleted(response.data[0].isDeleted);
});
}, [argu]);
const editData = () => {
axios.put("http://localhost:8000/upusermst/" + argu, {
CmpnyCode,
UserID,
UserFullName,
UserDetail,
LoginID,
Password,
UserPin,
UserEmailID,
UserFP,
Photo,
IsActive,
LicCount,
DateCreated,
CreatedBy,
RecordChanged,
LocationID,
isValid,
isDeleted,
});
history.push("/usermst");
};
return (
<div className="App">
<div className="auth-wrapper">
<div className="auth-inner">
<form enctype="multipart/form-data" onSubmit={() => editData()}>
<h3> Edit User Master</h3>
<div>
<div className="form-class8">
<div className="form-group">
<label>Company Code</label>
<input
type="text"
className="form-control"
placeholder="CompanyCode"
value={CmpnyCode}
onChange={(e) => {
setCmpnyCode(e.target.value);
}}
name="CmpnyCode"
/>
</div>
<div className="form-group">
<label>UserID</label>
<input
type="text"
className="form-control"
placeholder="UserID"
value={UserID}
onChange={(e) => {
setUserID(e.target.value);
}}
name="UserID"
/>
</div>
<div className="form-group">
<label>UserFullName</label>
<input
type="text"
className="form-control"
placeholder="UserFullName"
value={UserFullName}
onChange={(e) => {
setUserFullName(e.target.value);
}}
name="UserFullName"
/>
</div>
<div className="form-group">
<label>UserDetail</label>
<input
type="text"
className="form-control"
placeholder="UserDetail"
onChange={(e) => {
setUserDetail(e.target.value);
}}
name="UserDetail"
value={UserDetail}
/>
</div>
<div className="form-group">
<label>LoginID</label>
<input
type="text"
className="form-control"
placeholder="LoginID"
onChange={(e) => {
setLoginID(e.target.value);
}}
name="LoginID"
value={LoginID}
/>
</div>
<div className="form-group">
<label>Password</label>
<input
type="text"
className="form-control"
placeholder="Password"
onChange={(e) => {
setPassword(e.target.value);
}}
name="Password"
value={Password}
/>
</div>
<div className="form-group">
<label>UserPin</label>
<input
type="text"
className="form-control"
placeholder="UserPin"
onChange={(e) => {
setUserPin(e.target.value);
}}
name="UserPin"
value={UserPin}
/>
</div>
<div className="form-group">
<label>UserEmailID</label>
<input
type="email"
className="form-control"
placeholder="UserEmailID"
onChange={(e) => {
setUserEmailID(e.target.value);
}}
name="UserEmailID"
value={UserEmailID}
/>
</div>
</div>
<div className="form-class8">
<div className="form-group">
<label>UserFP</label>
<input
type="file"
className="form-control"
placeholder="UserFP"
onChange={(e) => {
setUserFP(e.target.value);
}}
name="UserFP"
value={UserFP}
/>
</div>
<div className="form-group">
<label>Photo</label>
<input
type="file"
className="form-control"
placeholder="Photo"
onChange={(e) => {
setPhoto(e.target.value);
}}
name="Photo"
value={Photo}
/>
</div>
<div className="form-group">
<label>IsActive</label>
<input
type="text"
className="form-control"
placeholder="IsActive"
onChange={(e) => {
setIsActive(e.target.value);
}}
name="IsActive"
value={IsActive}
/>
</div>
<div className="form-group">
<label>LicCount</label>
<input
type="text"
className="form-control"
placeholder="LicCount"
onChange={(e) => {
setLicCount(e.target.value);
}}
name="LicCount"
value={LicCount}
/>
</div>
<div className="form-group">
<label>DateCreated</label>
<input
type="text"
className="form-control"
placeholder="DateCreated"
onChange={(e) => {
setDateCreated(e.target.value);
}}
name="DateCreated"
value={DateCreated}
/>
</div>
<div className="form-group">
<label>CreatedBy</label>
<input
type="text"
className="form-control"
placeholder="CreatedBy"
onChange={(e) => {
setCreatedBy(e.target.value);
}}
name="CreatedBy"
value={CreatedBy}
/>
</div>
<div className="form-group">
<label>RecordChanged</label>
<input
type="text"
className="form-control"
placeholder="RecordChanged"
onChange={(e) => {
setRecordChanged(e.target.value);
}}
name="RecordChanged"
value={RecordChanged}
/>
</div>
<div className="form-group">
<label>LocationID</label>
<input
type="text"
className="form-control"
placeholder="LocationID"
onChange={(e) => {
setLocationID(e.target.value);
}}
name="LocationID"
value={LocationID}
/>
</div>
</div>
<div className="form-class8">
<div className="form-group">
<label>isValid</label>
<input
type="date"
className="form-control"
placeholder="isValid"
onChange={(e) => {
setisValid(e.target.value);
}}
name="isValid"
value={isValid}
/>
</div>
<div className="form-group">
<label>isDeleted</label>
<input
type="date"
className="form-control"
placeholder="isDeleted"
onChange={(e) => {
setisDeleted(e.target.value);
}}
name="isDeleted"
value={isDeleted}
/>
</div>
</div>
<button className="btn btn-primary btn-block">Edit</button>
</div>
</form>
</div>
</div>
</div>
);
}
export default withRouter(UserMaster_Edit);
The fields that you are looking for are UserFP and Photo which are of type file.
Node backend:
const multer = require("multer");
const upload = multer({ storage: multer.memoryStorage() });
app.put("/upusermst/:UserID", upload.single("Photo"), (req, res) => {
const userid = req.params.UserID;
const CompanyCode = req.body.CmpnyCode;
const UserID = req.body.UserID;
const UserFullName = req.body.UserFullName;
const UserDetail = req.body.UserDetail;
const LoginID = req.body.LoginID;
const Password = req.body.Password;
const UserPin = req.body.UserPin;
const UserEmailID = req.body.UserEmailID;
const UserFP = req.body.UserFP;
const Photo = req.body.Photo;
const Photo2 = req.file;
const IsActive = req.body.IsActive;
const LicCount = req.body.LicCount;
const DateCreated = req.body.DateCreated;
const CreatedBy = req.body.CreatedBy;
const RecordChanged = req.body.RecordChanged;
const LocationID = req.body.LocationID;
const isValid = req.body.isValid;
const isDeleted = req.body.isDeleted;
console.log(Photo2);
db.query(
"UPDATE usermst SET CmpnyCode=?,UserID=?,UserFullName=?,UserDetail=?,LoginID=?,Password=?,UserPin=?,UserEmailID=?,UserFP=?,Photo=?,IsActive=?,LicCount=?,DateCreated=?,CreatedBy=?,RecordChanged=?,LocationID=?,isValid=?,isDeleted=? WHERE UserID=?",
[
CompanyCode,
UserID,
UserFullName,
UserDetail,
LoginID,
Password,
UserPin,
UserEmailID,
UserFP,
Photo,
IsActive,
LicCount,
DateCreated,
CreatedBy,
RecordChanged,
LocationID,
isValid,
isDeleted,
userid,
],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
}
);
});
Note that there is variable named Photo already but that was what I did before, now I am doing req.file for Photo2 and that is resulting to undefined.
I would really appreciate if someone can edit the code for me for better understanding with some explanation as to why I may be getting undefined for "Photo2"
After a lot of digging I finally figured out the problem.
I had not installed jQuery hence the put request being sent by axios was giving the result undefined in the backend. I used fetch instead and it worked.
The code is now as follows:
The form:
const uploadPhoto = (event, argu) => {
event.preventDefault();
const formData = new FormData();
formData.append("avatar", Photo);
fetch("http://localhost:8000/uploadphoto/" + argu, {
method: "PUT",
body: formData,
});
};
<form enctype="multipart/form-data">
<div className="form-group">
<label>Photo</label>
<input
type="file"
className="form-control"
placeholder="Photo"
onChange={(e) => {
setPhoto(e.target.files[0]);
}}
id="Photo"
name="Photo"
/>
</form>
Backend:
const multer = require("multer");
const fs = require("fs");
const upload = multer({ dest: "uploads/" });
app.put("/uploadphoto/:UserId", upload.single("avatar"), (req, res) => {
const userid = req.params.userId;
const photo = req.file;
const fileType = photo.mimetype.split("/")[1];
let newFileName = photo.filename + "." + fileType;
fs.rename(
`./uploads/${photo.filename}`,
`./uploads/${newFileName}`,
function () {
console.log("file renamed and uploaded");
}
);
console.log(photo);
console.log("fileName ", newFileName);
db.query(
"UPDATE usermst SET Photo=? WHERE UserID=?",
[newFileName, userid],
(err, result) => {
console.log(err);
res.json({ result });
}
);
});```
Because file type inputs are not in e.target.value. The are in e.target.files. As you have only one image that would be e.target.files[0] in your case.
<input
type="file"
lassName="form-control"
placeholder="Photo"
onChange={(e) => {
setPhoto(e.target.files[0]);
}}
name="Photo"
/>
By the way, you can't just send file along with request. You need to use formData instead.
Check out my minimal example:
import { useState } from "react";
export default function PrivatePage(props) {
const [image, setImage] = useState(null);
const [createObjectURL, setCreateObjectURL] = useState(null);
const uploadToClient = (event) => {
if (event.target.files && event.target.files[0]) {
const i = event.target.files[0];
setImage(i);
setCreateObjectURL(URL.createObjectURL(i));
}
};
const uploadToServer = async (event) => {
const body = new FormData();
body.append("file", image);
const response = await fetch("/api/formidable", {
method: "POST",
body
});
};
return (
<div>
<div>
{createObjectURL&&<img height="500px" width="1000px" src={createObjectURL}/>}
<h4>Select Image</h4>
<input type="file" name="myImage" onChange={uploadToClient} />
<button
className="btn btn-primary"
type="submit"
onClick={uploadToServer}
>
Send to server
</button>
</div>
</div>
);
}

useSelector state returns undefined but the redux dev tool showing the value

I am fetching data from api and then store some detail in redux store and from redux store I am setting some values on browser localstorage.
I am using browser localstorage for conditional statement but because of undefined in or initial state inside the redux store my condtions are not executing.
My code:
const Login = () => {
const dispatch = useDispatch();
const { isAuth } = useSelector((state) => state.login);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const submitLoginForm = async (e) => {
e.preventDefault();
dispatch(loginPending());
const response = await fetch("https://localhost:44316/api/auth/login", {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
credentials: 'include',
body: JSON.stringify({
email,
password,
})
});
if(response.status === 200){
dispatch(loginSuccess());
debugger;
localStorage.setItem('auth',isAuth);
console.log(isAuth);
console.log(localStorage.getItem('auth'));
}
else{
dispatch(loginFailed());
}
};
if(JSON.parse(localStorage.getItem('auth')) === true){
return <Redirect to="/" />
}
return (
<React.Fragment>
<Navbar />
<div className="formContainer">
<h1>Login</h1>
<form className="loginForm" onSubmit={submitLoginForm}>
<div className="mb-3">
<label htmlFor="exampleInputEmail1" className="form-label">
Email address
</label>
<input
type="email"
className="form-control"
aria-describedby="emailHelp"
onChange={(e) => setEmail(e.target.value)}
/>
<div id="emailHelp" className="form-text">
We'll never share your email with anyone else.
</div>
</div>
<div className="mb-3">
<label htmlFor="exampleInputPassword1" className="form-label">
Password
</label>
<input
type="password"
className="form-control"
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<button type="submit" className="btn btn-primary">
Login
</button>
</form>
</div>
</React.Fragment>
);
};
My slice Contain:
loginSuccess: (state) => {
state.isLoading = false;
state.isAuth = true;
state.error = "";
}
I want to get isAuth value from redux store and then store it inside the browser local storage. But I am getting false value in my console
In the browser redux dev tool its showing the state change.

Categories