When I send username, password, email by postman it works and adds infos to mongodb schema but in login page at react it doesn't work. I would really appreciate if someone could help. Thank you so much.
React logic:
const [username, setUserName] = useState("");
const [password, setPassword] = useState("");
const [email, setEmail] = useState("");
const handleSubmit = async (e) =>{
console.log(".....");
e.preventDefault();
const res = await axios.post("/auth/register", {
username,
email,
password,
});
console.log(res)
};
Node.js logic:
router.post("/register", async (req, res) => {
console.log("here")
try{
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: hashedPassword,
});
const user = await newUser.save();
res.status(200).json(user);
} catch(err) {
console.log(err);
}
}
);
/////////////////////
app.use("/api/auth", authRoute);
app.use("/",(req,res)=>{
console.log("main url")
})
app.listen("3000",()=>{
console.log("backend running");
})
make sure that you send the request to the right route/server, maybe you miss-typed the port or the route itself.
I believe this line const res = await axios.post("/auth/register", {
isn't matching your backend app.use("/api/auth", authRoute);
Looks like you defined your register logic on /register
endpoint, BUT you are sending request to /auth/register
endpoint.
Try to change your React logic to send request to /register
endpoint:
const res = await axios.post("/register", {
username,
email,
password,
});