I have done client and server sign-in & sign-up for my project after fetching register API from the frontend it is showing "please fill all fields" error which i was provide the validation. I have filled all the fields properly but it is showing the error again and again.
**Here my backend code **
const express = require("express");
const router = express.Router();
const dotenv = require("dotenv");
dotenv.config({ path: "../config.env" });
const User = require("../models/UserModel");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const userCntrl = {
userregsiter: async (req, res) => {
try {
const { role, username, email, mobile, password, confirmpassword } =
req.body;
if (
!role || !username || !email || !mobile || !password || !confirmpassword
) {
return res.status(400).json({ error: "**please fill all the fields**" });
}
if (!validateEmail(email)) {
return res.status(400).json({ error: "**invalid email check again**" });
}
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ error: "**user already have exits**" });
}
if (password.length < 6) {
return res
.status(400)
.json({ error: "**password must be least 06 character**" });
}
// if (password !== confirmpassword) {
// return res.status(400).json({ error: "**passsword do not match**" });
// }
const passwordHash = await bcrypt.hash(password, 12);
console.log(passwordHash);
const newUser = new User({
role,
username,
email,
mobile,
password: passwordHash,
confirmpassword: passwordHash,
});
console.log(newUser);
const saveUser = await newUser.save();
console.log(saveUser);
res.status(200).json({ msg: "Register succusfully" });
} catch (error) {
console.log(error);
return res.status(500).json({ error });
}
},
protected: (req, res) => {
res.json({ msg: "auth is working " });
},
userlogin: async (req, res) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res
.status(400)
.json({ error: "**please fill email and password**" });
}
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ error: "**This email does not exist**" });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch || !email) {
return res
.status(400)
.json({ error: "** Invalid email or password**" });
}
const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET_KEY);
res.json({ token });
// res.json({ msg: "Login success!" });
} catch (error) {
return res.status(500).json({ error });
console.log(error);
}
},
};
function validateEmail(email) {
const re =
/^(([^<>()\[\]\\.,;:\s@"] (\.[^<>()\[\]\\.,;:\s@"] )*)|(". "))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9] \.) [a-zA-Z]{2,}))$/;
return re.test(email);
}
module.exports = userCntrl;
Here my frontend code
import React, { useState } from "react";
import "./UserRegister.css";
import { Link } from "react-router-dom";
import ing from "../assets/ing.png";
import { message } from "antd";
const UserRegister = () => {
const [role, setRole] = useState("");
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [mobile, setMobile] = useState("");
const [password, setPassword] = useState("");
const [confrimpassword, setConfrimpassword] = useState("");
console.log({
role,
username,
email,
mobile,
password,
confrimpassword,
});
const fetchRegister = () => {
fetch("/api/user/userregsiter", {
method: "post",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
role,
username,
email,
mobile,
password,
confrimpassword,
}),
})
.then((res) => res.json())
.then((data) => {
console.log(data);
if (data.msg) {
message.success(data.msg);
} else {
message.error(data.error);
}
});
};
return (
<div className="body_body">
<div className="signup-container">
<div className="welcome-img">
<img src={ing} alt="welcome image" height="350px" width="450px" />
</div>
<div >
<h2>Create your Account Today ! </h2>
<p >Sign Up</p>
<div >
<div >
<span ></span>
<label className="select_label" for="role">
Choose your role
</label>
<select
id="role"
className="role_select"
value={role}
onChange={(e) => setRole(e.target.value)}
>
<option value="Student">Student</option>
<option value="Company">Company</option>
<option value="Mentor">Mentor</option>
</select>
</div>
<div >
<input
type="text"
placeholder="Please enter your username "
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<span ></span>
</div>
<div >
<input
type="text"
placeholder="Enter your email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<span ></span>
</div>
<div >
<input
type="text"
placeholder=" Enter Mobile No"
name="mobile"
value={mobile}
onChange={(e) => setMobile(e.target.value)}
/>
<span ></span>
</div>
<div >
<input
type="password"
placeholder="Enter Password"
name="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<span ></span>
</div>
<div >
<input
type="password"
name="Confirmpassword"
placeholder="Enter Confirm Password"
value={confrimpassword}
onChange={(e) => setConfrimpassword(e.target.value)}
/>
<span ></span>
</div>
<p >
Already have an account?
<Link to="login">Login</Link>
</p>
<div >
<button type="submit" onClick={() => fetchRegister()}>
Sign Up
</button>
</div>
</div>
</div>
</div>
</div>
);
};
export default UserRegister;
CodePudding user response:
You have a typo in your JSON.stringify() on your frontend code.
body: JSON.stringify({
role,
username,
email,
mobile,
password,
confrimpassword,
}),
You have misspelled confirmpassword.