请任何人都可以帮我找出错误或错误吗?
please can anyone help me to find out the mistake or error?
从前端获取寄存器 API 后,我已经为我的项目完成了客户端和服务器登录和注册,它显示“请填写所有字段”错误,我提供了验证。我已经正确填写了所有字段,但它一次又一次地显示错误。
**这是我的后端代码**
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;
这是我的前端代码
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 class="form-container">
<h2>Create your Account Today ! </h2>
<p class="title">Sign Up</p>
<div class="signup-form">
<div class="form-item selector">
<span class="item-indicator"></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 class="form-item fullname">
<input
type="text"
placeholder="Please enter your username "
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<span class="item-indicator"></span>
</div>
<div class="form-item email">
<input
type="text"
placeholder="Enter your email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<span class="item-indicator"></span>
</div>
<div class="form-item confirm-password">
<input
type="text"
placeholder=" Enter Mobile No"
name="mobile"
value={mobile}
onChange={(e) => setMobile(e.target.value)}
/>
<span class="item-indicator"></span>
</div>
<div class="form-item password">
<input
type="password"
placeholder="Enter Password"
name="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<span class="item-indicator"></span>
</div>
<div class="form-item confirm-password">
<input
type="password"
name="Confirmpassword"
placeholder="Enter Confirm Password"
value={confrimpassword}
onChange={(e) => setConfrimpassword(e.target.value)}
/>
<span class="item-indicator"></span>
</div>
<p class="login">
Already have an account?
<Link to="login">Login</Link>
</p>
<div class="actions">
<button type="submit" onClick={() => fetchRegister()}>
Sign Up
</button>
</div>
</div>
</div>
</div>
</div>
);
};
export default UserRegister;
您的前端代码 JSON.stringify() 中有错字。
body: JSON.stringify({
role,
username,
email,
mobile,
password,
confrimpassword,
}),
您拼错了 confirmpassword。
从前端获取寄存器 API 后,我已经为我的项目完成了客户端和服务器登录和注册,它显示“请填写所有字段”错误,我提供了验证。我已经正确填写了所有字段,但它一次又一次地显示错误。
**这是我的后端代码**
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;
这是我的前端代码
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 class="form-container">
<h2>Create your Account Today ! </h2>
<p class="title">Sign Up</p>
<div class="signup-form">
<div class="form-item selector">
<span class="item-indicator"></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 class="form-item fullname">
<input
type="text"
placeholder="Please enter your username "
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<span class="item-indicator"></span>
</div>
<div class="form-item email">
<input
type="text"
placeholder="Enter your email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<span class="item-indicator"></span>
</div>
<div class="form-item confirm-password">
<input
type="text"
placeholder=" Enter Mobile No"
name="mobile"
value={mobile}
onChange={(e) => setMobile(e.target.value)}
/>
<span class="item-indicator"></span>
</div>
<div class="form-item password">
<input
type="password"
placeholder="Enter Password"
name="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<span class="item-indicator"></span>
</div>
<div class="form-item confirm-password">
<input
type="password"
name="Confirmpassword"
placeholder="Enter Confirm Password"
value={confrimpassword}
onChange={(e) => setConfrimpassword(e.target.value)}
/>
<span class="item-indicator"></span>
</div>
<p class="login">
Already have an account?
<Link to="login">Login</Link>
</p>
<div class="actions">
<button type="submit" onClick={() => fetchRegister()}>
Sign Up
</button>
</div>
</div>
</div>
</div>
</div>
);
};
export default UserRegister;
您的前端代码 JSON.stringify() 中有错字。
body: JSON.stringify({
role,
username,
email,
mobile,
password,
confrimpassword,
}),
您拼错了 confirmpassword。