This is the Registration component in src folder
import React, {useState} from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
const Registration = () => {
const [formData, setFormData] = useState({
username: '',
email: '',
password: '',
});
const [error, setError] = useState('');
const navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
try {
await axios.post('http://localhost:5000/register/reg', formData);
console.log('Registration successful');
setError(''); // Reset error on success
navigate('/MyCart'); // Redirect to login page
} catch (error) {
console.error('Registration failed');
console.error('Registration failed', error.response.data);
setError(error.response.data.message); // Set error message
}
};
return (
<div>
<h2>Registration</h2>
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" name="username" value={formData.username} onChange={(e) => setFormData(e.target.value)} required />
</label><br />
<label>
Email:
<input type="email" name="email" value={formData.email} onChange={(e) => setFormData(e.target.value)} required />
</label><br />
<label>
Password:
<input type="password" name="password" value={formData.password} onChange={(e) => setFormData(e.target.value)} required />
</label><br />
<button type="submit">Register</button>
</form>
{error && <p style={{ color: 'red' }}>{error}</p>}
</div>
);
};
export default Registration;
This is the users model
const mongoose = require("mongoose")
const UserSchema = new mongoose.Schema({
username: {type: String, required:true, unique:true},
email:{type:String, required:true, unique:true},
password: {type:String, required:true},
isAdmin:{
type: Boolean, default:false
}
},
{timestamps: true}
);
//module.exports = mongoose.model("users", UserSchema);
const User = mongoose.model('users', UserSchema);
module.exports = User;
This the register.route.js under routes folder
const express = require('express');
const User = require('../database/models/users');
const bcrypt = require('bcrypt');
const router = express.Router();
router.post('/', async (req, res) => {
try {
const { username, email, password, age } = req.body;
// Hash the password
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);
// Create a new user with the hashed password
const user = new User({ username, email, password: hashedPassword, age });
// Save the user to the database
await user.save();
// Send a success response
res.status(200).json({
status: 'success',
data: {
user
}
});
} catch (err) {
let errorMessage;
if (err.code === 11000) {
// Handle duplicate key error
errorMessage = 'Email already exists';
} else if (err.name === 'ValidationError') {
// Handle Mongoose validation error
errorMessage = Object.values(err.errors).map(val => val.message).join(', ');
} else {
// Generic error message
errorMessage = err.message;
}
// Send a failed response
res.status(500).json({
status: 'failed',
message: errorMessage
});
}
});
module.exports = router;
This is the sever.js
const express = require("express");
const app = express();
const dotenv = require("dotenv");
const connectDB = require('./database/connect');
const cors = require("cors");
const bodyParser = require('body-parser');
const register = require("./routes/register.route");
const ProductsRoute = require("./routes/Product");
connectDB(process.env.MONGO_URL);
app.use(express.json());
app.use("/reg", register);
app.use("/api/Product", ProductsRoute);
app.use(cors());
app.use(bodyParser.json());
app.listen(PORT, ()=> {
console.log(`Server is running on http://localhost:${PORT}`);
})
I have imported Registration component to App.js and wrap it with BrowserRouter
<Route path='/reg' element={<Registration/>}/>
I Got this console error message "Failed to load resource: the server responded with a status of 500(Internal server Error). I have tried to specify origin to the cors, as app.use(cors({ origin:'http://localhost:5000/' })); but it didn't work.
I got axios error and cors "Access-header-missing" errors before and make some changes to handle those errors.
I am beginner to MERN stack. So ,Please help me to make this work..
.
In the frontend, you can add one more field, "age," and utilize a single onChange function to handle all input fields.
And also modify the schema like this: