React, Node: Variable shows undefined on app.post() - node.js

Not sure if I've done it correctly on the server or client side, but in the client side when I console.log(values) they appear, but in server, I get undefined. But when i do enter the right credentials for a user in the database i get status:ok, so something is found. And also a extra bug is i cannot to the post request twice, then i get the error: Error: Cannot enqueue Handshake after invoking quit.
Client Code:
class Login extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
const email = data.get('email');
const password = data.get('password');
fetch('/authentication', {
method: 'POST',
body: JSON.stringify({
"email": email,
"password": password
}),
}).then(function (response) {
if (response.ok) {
alert("Login Successful!");
} else {
console.log("Failed");
}
});
console.log("Email: " + email);
console.log("pwd: " + password);
}
render() {
return (
<form className="col s12 m12 l12" onSubmit={this.handleSubmit}>
<div className="row">
<div className="col s12 center-align">
<img className="logo" src="images/bibdata-center.png" alt="BibData Logo"/>
</div>
<div className="input-field col s12">
<i className="material-icons prefix">email</i>
<input id="email" name="email" type="email" className="validate" onChange={this.handleEmailChange}/>
<label htmlFor="email">Email</label>
</div>
</div>
<div className="row">
<div className="input-field col s12">
<i className="material-icons prefix">lock</i>
<input id="password" name="password" type="password" className="validate" onChange={this.handlePasswordChange}/>
<label htmlFor="password">Password</label>
</div>
</div>
<div className="row">
<div className="col s12 m6 l6 center-align">
<button className="btn waves-effect btn-large waves-light" type="submit" value="Submit" name="action">Sign in
<i className="material-icons right">send</i>
</button>
</div>
<div className="col s12 m6 l6 center-align">
<button className="btn waves-effect btn-large waves-light blue" type="submit" name="action"
onClick={() => renderReactComponent(newUser, 'root')}>
Register
</button>
</div>
</div>
<div className="row">
<div className="col s12 center-align">
<a href="#" onClick={() => renderReactComponent(forgotPassword, 'root')}>
<span className="helper-text grey-text text-darken-1"
data-error="wrong" data-success="right">
Forgot password?
</span>
</a>
</div>
</div>
</form>
);
}
}
And Server Code:
app.post('/authentication', function (req, res) {
connection.connect();
let email = req.body.email;
let password = req.body.password;
console.log(email);
console.log(password);
connection.query('SELECT * FROM user WHERE email = ? AND password = ?',
[email, password], function (error, results, fields) {
if (error) {
return res.status(500).send(error);
}
return res.send({ error: false, data: results, message: 'ok'})
});
connection.end();
});
All help will be appreciated!

When you make your fetch call to /authentication endpoint, you are sending serialized JSON data in your request body. The server however has no means of knowing that you have actually sent an JSON. When posting JSON, you must indicate that by providing appropriate content-type header.
In this case your fetch options (2nd param) should have one more property like this:
...
headers: {
"Content-Type": "application/json",
},
...
This is assuming, you have already setup body-parser or another similar module on your server side code which can parse JSON request body.

Related

How to check if a username is taken in Mongo Schema with an AJAX API call

I am trying to create a registration form where a potential user is typing in their desired username it checks against the existing Mongo DB User Schema to see if that exact name exists.
The form I have is here:
<form class="needs-validation" action="/register" method="POST" novalidate>
<div class="text-center mb-3">
<p class="lead">Welcome to the team! We just need a few things to get started.</p>
<div class="row">
<div class="col-md-6 mb-4">
<div class="form-outline">
<input
type="text"
id="first_name"
name="first_name"
class="form-control"
required
/>
<label class="form-label" for="first_name"
>First name</label
>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Thats not right</div>
</div>
</div>
<div class="col-md-6 mb-4">
<div class="form-outline">
<input
type="text"
id="last-name"
name="last-name"
class="form-control"
required
/>
<label class="form-label" for="last-name"
>Last name</label
>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Thats not right</div>
</div>
</div>
</div>
<!-- Email input -->
<div class="form-outline mb-4">
<input
type="email"
id="register_email"
name="register_email"
class="form-control"
required
/>
<label class="form-label" for="register_email">Email</label>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Thats not right</div>
</div>
<div class="text-center mb-3">
<div class="form-outline mb-4">
<input type="text" id="register_username" name="register_username" class="form-control" placeholder="enter your username" required />
<label class="form-label" for="register_username">Username</label>
<div id="username-check"></div>
</div>
<!-- Password input -->
<div class="form-outline mb-4">
<input type="password" id="register_password" name="register_password" class="form-control" required/>
<label class="form-label" for="register_password">Password</label>
</div>
</div>
<!-- Submit button -->
<div class="text-center">
<button type="submit" id="register" class="btn btn-lg btn-rounded bg-insider link-dark mb-3 fw-bold" disabled>
Lets Go! <i class="fa-solid fa-gauge-max"></i>
</button>
</div>
</form>
I have this script code working on the page to take the user input and check to a get route that should be checking my MongoDB:
$('#register_username').on('keyup', function () {
$.get('/usercheck?username=' + $(this).val().toLowerCase(), function (response) {
$('#username-check').text(response.message);
console.log('')
var btn = document.getElementById('register');
btn.disabled = true;
if ($('#username-check').html() === "user exists") {
$('#username-check').text('username not available').css('color', 'red');
}
else {
console.log($('#register_username').val())
$('#username-check').text('username is available').css('color', 'green');
btn.disabled = false;
}
})
});
This is the route it calls to check the database:
var express = require("express"),
router = express.Router(),
passport = require("passport"),
User = require("../models/user");
router.get('/usercheck', function(req, res) {
console.log(req.query);
User.findOne({username: req.query.register_username}, function(err, username){
if(err) {
console.log(err);
}
var message;
if(username) {
console.log(username);
message = "user exists";
console.log(message);
} else {
message= "user doesn't exist";
console.log(message);
}
res.json({message: message});
});
});
module.exports = router;
In case this helps, this is the user Schema in the database:
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
username: String,
password: String,
email: String,
isAdmin: { type: Boolean, default: false }
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User",UserSchema);
I am not sure what I am missing but anything would be extremely helpful. Thanks in advance!
Just so this question can be closed successfully:
Changing /usercheck?username= to /usercheck?register_username= did the trick, because this query param was used in the form:
$('#register_username').on('keyup', function () {
$.get('/usercheck?register_username=' + $(this).val().toLowerCase(), function (response) {
$('#username-check').text(response.message);
console.log('')
var btn = document.getElementById('register');
btn.disabled = true;
if ($('#username-check').html() === "user exists") {
$('#username-check').text('username not available').css('color', 'red');
}
else {
console.log($('#register_username').val())
$('#username-check').text('username is available').css('color', 'green');
btn.disabled = false;
}
})
});

req.body() is getting empty while inserting data in MERN

I have MERN project where i have to simply put my form data in my database. All looking good but data is not inserting. while there is no error also.
I have done console.log(req.body). after i getting empty {}.
As i have tried so many previous question in stackoverflow but noe of them helps me
this is my screenshot of console of my browser
Showing staus 201 but data is not going in my database
How to debug this error. I have tried all solution. Atleast tell me the possible reasons of this error. it will help me a lot. i am trying from full 1 day
userSchema
const userSchema = new mongoose.Schema({
identity: {
type: String,
},
names: {
type: String,
},
phone: {
type: String,
},
email: {
type: String,
},
city: {
type: String,
},
address: {
type: String,
},
subject: {
type: String,
},
classes: {
type: String,
},
message: {
type: String,
},
})
const USER = mongoose.model("USER", userSchema)
module.exports = USER
register.js(frontend)
const Register = () => {
const [newUser, setNewUser] = useState({
identity: "",
names: "",
phone: "",
email: "",
city: "",
address: "",
subject: "",
classes: "",
message: "",
});
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData();
formData.append("identity", newUser.identity);
formData.append("names", newUser.names);
formData.append("phone", newUser.phone);
formData.append("email", newUser.email);
formData.append("city", newUser.city);
formData.append("address", newUser.address);
formData.append("subject", newUser.subject);
formData.append("classes", newUser.classes);
formData.append("message", newUser.message);
axios({
method: "post",
url: "/register",
data: formData,
headers: { "Content-Type": "application/json" },
})
.then((response) => {
console.log(response);
})
.then((data) => {
console.log(data);
})
.catch((error) => {
if (error.response) {
console.log(error.response.data);
}
});
};
const handleChange = (e) => {
setNewUser({ ...newUser, [e.target.name]: e.target.value });
};
return (
<>
<div class="container register mt-5">
<h1 class="well text-register shadow p-4 rounded-3">
Join as{" "}
<label class="student">
[{" "}
<img src="https://img.icons8.com/external-vitaliy-gorbachev-lineal-color-vitaly-gorbachev/60/000000/external-man-avatars-vitaliy-gorbachev-lineal-color-vitaly-gorbachev-12.png" />{" "}
Parent/Student{" "}
<img src="https://img.icons8.com/external-justicon-lineal-color-justicon/64/000000/external-student-back-to-school-justicon-lineal-color-justicon.png" />{" "}
]
</label>
<h1 class="well text-register down">
<i class="fas fa-arrow-right"></i> Hey! If you are looking for right
tutor near by your location. Don't worry you are at right place.{" "}
<i class="fas fa-arrow-left"></i>
</h1>
</h1>
<div class="col-lg-12 well rounded-3">
<div class="row mt-5 ">
<form onSubmit={handleSubmit} method = "post" class="shadow p-5">
<div class="col-sm-12">
<div class="row">
<div class="col-sm-12 form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i> Your Identity
</label>
<input
type="text"
placeholder="Write Student or Parent"
class="form-control"
name="identity"
id="identity"
value={newUser.identity}
onChange={handleChange}
/>
</div>
</div>
<div class="form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i> Name
</label>
<input
type="text"
placeholder="Enter Your Full Name Here.."
class="form-control"
name="names"
id="names"
value={newUser.names}
onChange={handleChange}
/>
</div>
<div class="form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i> Phone Number
</label>
<input
type="text"
placeholder="Enter Phone Number Here.."
class="form-control"
name="phone"
id="phone"
value={newUser.phone}
onChange={handleChange}
/>
</div>
<div class="form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i> Email Address
</label>
<input
type="text"
placeholder="Enter Email Address Here.."
class="form-control"
name="email"
id="email"
value={newUser.email}
onChange={handleChange}
/>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i> City
</label>
<input
type="text"
placeholder="Enter City Name Here.."
class="form-control"
name="city"
id="city"
value={newUser.city}
onChange={handleChange}
/>
</div>
<div class="col-sm-6 form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i> Address
</label>
<textarea
placeholder="Enter Address Here.."
rows="3"
class="form-control"
name="address"
id="address"
value={newUser.address}
onChange={handleChange}
></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i> Subject
</label>
<input
type="text"
placeholder="Enter Subject Here.."
class="form-control"
name="subject"
id="subject"
value={newUser.subject}
onChange={handleChange}
/>
</div>
<div class="col-sm-6 form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i>Student Class
</label>
<input
type="text"
placeholder="Enter Student Class"
class="form-control"
name="classes"
id="classes"
value={newUser.classes}
onChange={handleChange}
/>
</div>
</div>
<div class="form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i> Message
</label>
<textarea
placeholder="Enter Any message you have for us..."
rows="3"
class="form-control"
name="message"
id="message"
value={newUser.message}
onChange={handleChange}
></textarea>
</div>
<button value="register" type="submit" class="btn btn-lg btn-info">
Submit
</button>
</div>
</form>
</div>
</div>
</div>
</>
);
};
auth.js
router.get("/", (req, res) => {
res.send("hello, i am communicating with router");
})
router.post("/register", async (req, res) => {
const { identity, names, phone, email, city, address, subject, classes, message } = req.body
console.log(req.body)
try {
const user = new User({identity ,names, phone,email,city,address, subject, classes, message })
await user.save()
res.status(201).json({ message: "user registered successfulluy" })
} catch (err) {
console.log(err)
}
})
module.exports = router
app.js
const port = 5000
env.config({path: "../server/config.env"})
require("../server/db/conn")
app.use(cors());
app.use(express.json())
app.use(require("../server/router/Auth"))
app.listen(port, (err) => {
if (err) {
return console.error(err);
}
return console.log(`server is listening on ${port}`);
});
Please help. i have tried so many times!!
Thankyou!!!
Modify Your HandleSubmit function, do not use formData to submit your data as application/json
Instead, just use your current React State
const handleSubmit = (e) => {
e.preventDefault();
axios({
method: "post",
url: "/register",
data: JSON.stringify(newUser),
headers: { "Content-Type": "application/json" },
})
.then((response) => {
console.log(response);
})
.then((data) => {
console.log(data);
})
.catch((error) => {
if (error.response) {
console.log(error.response.data);
}
});
};

Axios throwing Internal server error but api url works

I hope you are all safe.
My problem:
the URL is working fine, there is no undefined URL error there. when i entered good credentials, it works fine and take me to the location i wish. But anytime i am trying to view the errors, it doesn't appear. Even, in the if condition i try to console.log(res.data.errors) but nothing shows. Even console.log("Hello it not working") doesn't work at all in the if condition... I am confused. Would u help please? but the else works fine. what am i doing wrong please?
import React, { useState } from "react";
import { Link } from "react-router-dom";
import SideBar from "../components/SideBar";
import "./profil.css";
import axios from "axios";
function Profil() {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const handleLogin = (e) => {
e.preventDefault();
const emailError = document.querySelector(".email.error");
const passwordError = document.querySelector(".password.error");
axios({
method: "post",
url: `${process.env.REACT_APP_API_URL}api/user/login`,
withCredentials: true,
data: {
email,
password,
},
})
.then((res) => {
if (res.data.errors) {
emailError.innerHTML = res.data.errors.email;
passwordError.innerHTML = res.data.errors.password;
} else {
window.location = "/";
}
})
.catch((err) => {
if (err.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
} else if (err.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(err.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', err.message);
}
console.log(err.config);
});
};
return (
<>
<SideBar />
<div className="form-container">
<input type="checkbox" id="flip" />
<div className="cover">
<div className="front">
<img src="dog-4977599_1920.jpg" alt="" />
<div className="text">
<span className="text-i">Welcome to ChablisLAB</span>
<span className="text-j">Please Login before continue</span>
</div>
</div>
<div className="back">
<img className="backImg" src="diary-92652_1920.jpg" alt="" />
<div className="text">
<span className="text-i">Welcome to ChablisLAB</span>
<span className="text-j">Just a few step to gain access</span>
</div>
</div>
</div>
<form>
<div className="form-content">
<div className="login_form">
<div className="title">Login</div>
<div className="input_boxes">
<div className="input_box">
<i className="bx bx-envelope"></i>
<input
type="email"
onChange={(e) => setEmail(e.target.value)}
value={email}
placeholder="Enter your email"
/>
</div>
<div className="email error"></div>
<div className="input_box">
<i className="bx bxs-lock"></i>
<input
type="password"
onChange={(e) => setPassword(e.target.value)}
value={password}
placeholder="Password"
/>
</div>
<div className="password error"></div>
<div className="box_forgot_pass">
<Link to="#">Forgot password?</Link>
</div>
<div className="button input_box">
<input onClick={handleLogin} type="submit" value="Login" />
</div>
<div className="text sign-up-text">
Don't have an account?
<label htmlFor="flip">Signup now</label>
</div>
</div>
</div>
</div>
</form>
</div>
</>
);
}
export default Profil;
.error{
color: red;
}
<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>
I think you need to console res.data.errors before you add if condition. There might be the chance you are putting conditions on the wrong properties which you are not getting in return as a response.
axios({
method: "post",
url: `${process.env.REACT_APP_API_URL}api/user/login`,
withCredentials: true,
data: {
email,
password,
},
})
.then((res) => {
console.log(res.data.errors, res.data); //check like this then put condition if you are getting res.data.errors property in response
if (res.data.errors) {
emailError.innerHTML = res.data.errors.email;
passwordError.innerHTML = res.data.errors.password;
} else {
window.location = "/";
}
})

Data is not getting captured in mongodb

Data is not getting captured in mongodb . For frontend I am using angular and at backend I am using node js. I tested the backend api using postman , data is getting captured in mongoDb , where as when I am submitting from an angular form data is not getting captured.
//UI logic
<div class="row mt-5">
<div class="col-md-6 mx-auto">
<div class="card">
<div class="card-header">
<h3>Register</h3>
</div>
<div class="card-body">
<form>
<div class="form-group">
<label>Email:</label>
<input type="text" class="form-control" name="email" [(ngModel)]="registerUserData.email" email required>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control" name="password" [(ngModel)]="registerUserData.password" required>
</div>
<button (click)="registerUser()" class="btn btn-info float-right">Register</button>
</form>
</div>
</div>
</div>
</div>
//service
private urlR="http://localhost:3000/register";
private urlL="http://localhost:3000/login";
constructor(private httpClient:HttpClient) { }
registerUser(abc){
return this.httpClient.post<any>(this.urlR,abc);
}
//submit method
registerUser() {
this.authService.registerUser(this.registerUserData)
.subscribe(
res=> console.log(res),
err=> console.log(err)
)
}
//backend node
app.post('/register' , (req,res) => {
const newUser = new Expo({
email:req.body.email,
password:req.body.password
});
newUser.save( (err , registeredUser) => {
if(err) {
console.log(err);
} else {
res.status(200).send(registeredUser);
}
});
});

using React can I prevent sending empty strings from my inputs to my mongodb database during update?

I have inputs that take in information that is set to the state. The states initial values is set to empty strings. none of the inputs are required inputs so some may remain blank I then send the inputted information to the the API but that may send possible empty strings which would replaces information that I don't want to update.
I tried setting the initial states to undefined but i got the uncontrolled inputs error because I know undefined values would not be accepted in my database.
I have thought about maybe creating an array and pushing only the values that aren't equal to an empty string into it and then sending the array to the API.
import React from "react";
import API from "../../utils/API";
import { Link } from "react-router-dom";
import { storage } from "../../config/fire";
class ProfileEditor extends React.Component {
state = {
image: null,
url: "",
isActive: false,
emailaddress: "",
password: "",
confirm: "",
screenName: "",
securityQuestion: "",
securityAnswer: "",
birthDate: "",
gender: "",
phoneNumber: "",
cityState: "",
userPic: "",
}
handleChange = e => {
this.setState({
[e.target.name]: e.target.value
});
};
updateProfile = id => {
if (this.state.password.length > 0 && this.state.password.length < 6) {
alert(
`Choose a more secure password `
);
} else if (this.state.password !== this.state.confirm) {
alert("You Passwords do not match");
} else {
API.updateEditProfile(id, {
password: this.state.password,
screenName: this.state.screenName,
securityQuestion: this.state.securityQuestion,
securityAnswer: this.state.securityAnswer,
birthDate: this.state.birthDate,
gender: this.state.gender,
phoneNumber: this.state.phoneNumber,
cityState: this.state.cityState,
userPic: this.state.url
})
.then(function (response) {
console.log(response);
})
.catch(err => console.log(err));
document.getElementById("profileForm").reset();
}
}
handleImageSelected = event => {
this.uploadClick()
if (event.target.files[0]) {
const image = event.target.files[0];
this.setState(() => ({ image }));
}
}
handleUpload = () => {
const fullName = this.props.userInfo.firstname + "_" + this.props.userInfo.lastname;
const { image } = this.state;
const uploadTask = storage.ref(fullName + "/" + image.name).put(image);
uploadTask.on("state_changed",
(snapshot) => {
const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
this.setState({ progress: progress })
},
(error) => {
console.log(error);
},
() => {
storage.ref(fullName).child(image.name).getDownloadURL()
.then(url => {
this.setState({ url: url });
console.log(url)
})
});
}
uploadClick = () => {
this.setState({ isActive: !this.state.isActive })
};
render() {
const fullName = this.props.userInfo.firstname + " " + this.props.userInfo.lastname
const user = this.props.userInfo
console.log(this.props.userInfo.userPic)
return (
<div className="contentArea ">
<div className="profile-container">
<div className="profile-image">
<img src={this.props.userInfo.userPic} />
</div>
<div className="profile-info">
{fullName}
</div>
<section className="editProfile">
<div className="unchangeable">Name: {fullName} </div>
<div className="unchangeable">Email: {this.props.userInfo.emailaddress}</div>
<form id="profileForm">
<div className="profileInputs">
<input value={this.state.password} onChange={this.handleChange} type="password" placeholder="Password" name="password" ref="password" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.confirm} onChange={this.handleChange} type="password" placeholder="confirm password" name="confirm" ref="confirmPassword" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.securityQuestion} onChange={this.handleChange} type="text" placeholder="security question" name="securityQuestion" ref="securityQuestion" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.securityAnswer} onChange={this.handleChange} type="text" placeholder="Answer to security question" name="securityAnswer" ref="securityAnswer" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.screenName} onChange={this.handleChange} placeholder="screen name" name="screenName" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.birthDate} onChange={this.handleChange} type="text" placeholder="birth date" name="birthDate" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.Gender} onChange={this.handleChange} type="text" placeholder="gender" name="gender" className=" editInput" />
</div>
<div className="profileInputs">
<input value={this.state.phoneNumber} onChange={this.handleChange} type="text" placeholder="phone number" name="phoneNumber" className=" editInput" />
</div>
<div className="profileInputs">
<input value={this.state.cityState} onChange={this.handleChange} type="text" placeholder="city/state" name="cityState" className=" editInput" />
</div>
<div className="profileInputs"> Are you in a Relationship?
<input value={this.state.Gender} onChange={this.handleChange} type="text" placeholder="" name="gender" className=" editInput" />
</div>
</form>
</section>
<section className="feed ">
<div className="avatar">
<div className="avatarsect">
Upload Avatar
</div>
<input type="file" style={{ display: "none" }} onChange={this.handleImageSelected} ref={fileInput => this.fileInput = fileInput} />
<img className={this.state.isActive ? "uploadReady active" : "uploadReady"} src={this.state.url} alt="previewupload" height="40" width="50" />
<progress className={this.state.isActive ? "uploadReady active" : "uploadReady"} value={this.state.progress} max="100" />
<button className={this.state.isActive ? "uploadReady active" : "uploadReady"} onClick={this.handleUpload}>Upload</button>
<span className={this.state.isActive ? "uploadReady active" : "uploadReady"}></span>
<button type="button" className="button photo" onClick={() => this.fileInput.click()}><i class="fas fa-camera-retro"></i></button>
</div>
<br></br>
<br></br>
<div className="btnDiv">
<button onClick={() => this.updateProfile(this.props.userInfo.user_ID)} className="updateProfileBtn"> Update Profile</button>
</div>
<br></br>
<br></br>
<br></br>
<br></br>
</section>
</div>
</div>
);
}
}
export default ProfileEditor;
my Api
updateEditProfile:function(id,userData) {
console.log(userData)
console.log(id)
return axios.put("/api/usersData/" +id, userData);
},
my route and controller
router.route("/")
.post(usersDataController.findUserinfo)
.put(usersDataController.update)
router.route("/:id")
.put(usersDataController.updateByID);
updateByID: function(req, res) {
console.log(res)
db.usersData
.findByIdAndUpdate({ _id: req.params.id }, req.body,{new:true})
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
},

Resources