'Issue with form data send to database using axios in react js?
Hello everyone I have an issue I am doing login and registration form using react and node and mongodb at one point I am stuck at registration please let me know the solution.
Now first start with back end
This my controller file
const users = require('../models/users');
var bcrypt = require('bcryptjs');
const userList = async (req,res) =>{
let data = await users.find();
res.json(data);
}
const userAdd = async (req,res)=>{
let {name,email,password,cpassword} = req.body;
let data = new users({name,email,password,cpassword});
let response = await data.save();
let myToken = await data.getAuthToken();
res.status(200).json({message: 'User added sucessfully', token:myToken});
}
const userLogin = async (req,res)=>{
if(!req.body.email || !req.body.password){
res.status(301).json({message: 'error',message:"Please enter email and password"});
}
let user = await users.findOne({email: req.body.email});
var responseType = {
message: "ok"
}
if(user){
var match = await bcrypt.compare(req.body.password, user.password)
if(match){
let myToken = await user.getAuthToken();
responseType.message = 'login sucessfully';
responseType.token = myToken;
}else
{
responseType.message = 'Invalid Password';
}
}else{
responseType.message = 'Invalid Email ID';
}
console.log(user);
res.status(200).json({message: 'ok', data: responseType});
}
module.exports = {
userList,
userAdd,
userLogin
};
Now come to Front-End part
This is my registration form
const Register = () => {
const [inputField, setInputField] = useState({
name: '',
email: '',
password: '',
cpassword: ''
})
const inputHandler = (e) =>{
setInputField({...inputField, [e.target.name] : e.target.value})
}
const submitButton = async () =>{
if(validForm()){
let url = 'http://localhost:8080/users/add'
let options={
method: "post",
url: url,
headers:{
},
data: inputField
}
try{
let response = await axios(options)
console.log("res",response);
if(response.status == 200){
toast.success("Added Sucessfully");
}
}
catch(e){
toast.error("Something went wrong..!");
}
}else{
toast.error("Form Invalid..!");
}
}
Data is not store in MongoDB database. Thanks in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
