I am trying to add a new user with a registration form but when I fetch it with the post method to add to the database on MongoDB, I get the response on the screen as you see.
I can see data on the console after filling the registration form, I do that with console button.
Also, I can register a new user on Postman without any problem.
My code is here:
import { useState} from "react";
import { FaUser } from "react-icons/fa";
import { useNavigate } from "react-router-dom";
function Register() {
const [formData, setFormData] = useState({
name: "",
email: "",
password: "",
password2: "",
});
const { name, email, password, password2 } = formData;
const navigate=useNavigate();
const onChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
// console.log(formData);
}
const showData=(e)=>{
e.preventDefault();
console.log(formData);
}
const onSubmit = (e) => {
e.preventDefault();
if(password!==password2){
alert("Password does not match");
}else{
fetch("http://localhost:5000/api/users",{
mode: 'no-cors',
method:"POST",
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify({
name,
email,
password
})
})
.then(res=>res.json())
.then(data=>{
if(data.error){
console.log(data.error);
}else{
navigate("/login");
}
})
}
}
return (
<>
<section className="heading">
<h1>
<FaUser /> Register
</h1>
<p>Please create an account</p>
</section>
<section className="form">
<form onSubmit={onSubmit}>
<div className="form-group">
<input type="text" className="form-control" id="name"
name="name" value={name} placeholder="Enter your name"
onChange={onChange} />
</div>
<div className="form-group">
<input type="text" className="form-control" id="email"
name="email" value={email} placeholder="Enter your email"
onChange={onChange} />
</div>
<div className="form-group">
<input type="text" className="form-control" id="password"
name="password" value={password} placeholder="Enter your password"
onChange={onChange} />
</div>
<div className="form-group">
<input type="text" className="form-control" id="password2"
name="password2" value={password2} placeholder="Confirm your password2"
onChange={onChange} />
</div>
<div className="form-group">
<button type="submit" className="btn btn-block">Submit</button>
<button onClick={showData} className="btn btn-block">Console</button>
</div>
</form>
</section>
</>
)
}
export default Register