Register.js
import React from "react";
import { Button, Form, Input } from "antd";
import { Link } from "react-router-dom";
import axios from "axios";
import toast from "react-hot-toast";
function Register() {
const onFinish = async (values) => {
try {
const response = await axios.post("/api/user/register", values);
if (response.data.success) {
console.log(values);
toast.success(response.data.message);
} else {
toast.success(response.data.message);
}
} catch (error) {
toast.error("something went wrong");
}
};
return (
<div className="authentication">
{" "}
<div className="authentication-form card p-2">
{" "}
<h1 className="card-title">Nice to meet You</h1>
<Form layout="vertical" onFinish={onFinish}>
<Form.Item label="Name" name="name">
<Input placeholder="Name" />
</Form.Item>
<Form.Item label="Email" name="email">
<Input placeholder="Email" />
</Form.Item>
<Form.Item label="Password" name="password">
<Input placeholder="Password" type="password" />
</Form.Item>
<Button className="primary-button my-3" htmlType="submit">
Register
</Button>
<Link to="/login" className="anchor mt-2">
Click here to continue
</Link>
</Form>
</div>
</div>
);
}
export default Register;
server.js
const express = require("express");
const app = express();
require(`dotenv`).config;
const dbconfig = require("./config/dbconfig");
app.use(express.json())
const userRoute = require("./routes/userRoute");
app.use("/api/user", userRoute);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`node nerver started at port ${port}`));
userRoute.js
const express = require("express");
const router = express.Router();
const User = require("../models/userModel");
const bcrypt = require("bcryptjs");
router.post("/register", async (req, res) => {
try {
const userExists = await User.findOne({ email: req.body.email });
if (userExists) {
return res
.status(200)
.send({ message: "user exists alreayd", success: false });
}
const password = req.body.password;
const salt = await bcrypt.genSalt(10);
const hashedpassword = await bcrypt.hash(password, salt);
req.body.password = hashedpassword;
const newuser = new User(req.body);
await newuser.save();
res.status(200).send({ message: "user created", success: true });
} catch (error) {
return res.status(500).send({ message: "Error", success: false, error });
}
});
router.post("/login", async (req, res) => {
try {
} catch (error) {}
});
module.exports = router;
userModel.js
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema(
{
name: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
},
{ timestamps: true }
);
const userModel = mongoose.model("users", userSchema);
module.exports = userModel ;
What I have tried:
The Server Is Up And Running.
I tried both, only the get request works, is there any reason why post request doesn't work from the front end side or does is it something to do with the API that im sending my request to