How to make Register Form (MERN STACK)
A form in which we can take user response and store in the database.
Hello friends in this blog we will making the form in which we can take user respose through a form and store it using backend servor (node js) and store the response using the Mango DB
Tech used
Fronted | Backend | Database |
a) HTML ,CSS | a) NodeJs,Express Js | 1) Mongo Db |
b)Javascript | b) Javascript | 2)Mongoose |
Steps for making the form
1) On the step 1 we will make the form using the basic Html and CSS to make it beautiful we can use the library like bootstrap ,tailwind css.
I am giving you short templates example for design.
make sure to give the name field it is very important.
Use this template for the Javascript ..
import express from "express";
import path from 'path';
import mongoose from "mongoose";
const app =express();
const port =3000;
const users =[]
//used middleware
app.use(express.urlencoded({ extended: true }))
app.use(express.static(path.join(path.resolve(), 'public')))
//create a data base named "Hackathon"
mongoose
.connect('mongodb://127.0.0.1:27017/Hackathon', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('database connected'))
.catch(e => console.log(e))
// making the schema
const userSchema =new mongoose.Schema({
name:String,
email:String,
classes:String,
code:String,
})
const User =mongoose.model('User',userSchema)
app.set('view engine', 'ejs')
app.get('/',(req,res)=>{
res.render('index')
console.log("it is working ");
})
app.get('/success',(req,res)=>{
res.render('success');
})
app.post('/Register',async(req,res)=>{
const {name,email,classes,studentcode}=req.body;
const messageData=({
name: req.body.name,
email: req.body.email,
class: req.body.classes,
studentcode: req.body.code
})
await User.create(messageData);
console.log(messageData)
users.push(messageData)
res.redirect('/success')
})
app.get('/users',(req,res)=>{
res.json({
users,
})
})
app.listen(port,(req,res)=>{
console.log(`App is listening on port ${port}`)
})
<body>
<form>
<label for="email"><b>Name</b></label>
<input type="text" placeholder="Enter Name" name="name" id="email" required>
<label for="psw"><b>Password</b></label>
<input type="text" placeholder="Enter Password" name="psw" id="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" id="psw-repeat" required>
<hr>
<button type="submit" class="registerbtn">Register</button>
</form>
</body>