Here, we will write a program to create a registration form in node js. We will also be requiring mongoose database to send our registered data into the database. we will have three files here. one app.js which will contain our libraries which will be inside the main folder. another file will be signup.ejs, ejs is a framework where we design our front end pages and it will be stored in views folder and last page will be signup.js where we will create the schema and send the data, this file will be inside modal folder.
app.js in root directory.
require('dotenv').config()
const express=require("express");
var cookieParser = require("cookie-parser");
var session = require("express-session");
const app=express();
const router= express.Router();
const mongoose= require("mongoose");
const bodyParser=require('body-parser');
mongoose.set('strictQuery', false);
var User = require("./model/signUp");
app.set('view engine','ejs');
app.use(cookieParser());
app.use(
session({
key: "user_sid",
secret: "somerandonstuffs",
resave: false,
saveUninitialized: false,
cookie: {
expires: 600000,
},
})
);
app.use((req, res, next) => {
if (req.cookies.user_sid && !req.session.user) {
res.clearCookie("user_sid");
}
next();
});
// api for database
app.use(bodyParser.urlencoded({extended:true}));
router.get('/signUp',sessionChecker,(req,res)=>{
res.render('signUp');
})
router.post('/signUp',sessionChecker,(req, res) => {
var user = new User({
username: req.body.username,
email: req.body.email,
password:req.body.password,
});
user.save().then(()=>{
console.log("saved data");
})
.catch((err)=>{
console.log(err);
})
});
app.use('/',router);
app.listen(5000,()=>console.log('listren on 5000'));
signup.ejs in views directory
<div class="container row">
<div class="jumbotron col-sm-4 pull-center">
<form autocomplete="off" action="/signup" method="post">
<div class="form-group">
<label>Username:</label>
<input class="form-control" required type="text" name="username"/>
</div>
<div class="form-group">
<label>Email:</label>
<input class="form-control" required type="email" name="email"/>
</div>
<div class="form-group">
<label>Password:</label>
<input class="form-control" required type="password" name="password"/>
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" value="Sign Up"/>
</div>
</form>
</div>
</div>
signup.js in model directory
const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
var url="mongodb+srv://reactapp:admin1234@cluster0.l2ko6.mongodb.net/demo4?retryWrites=true&w=majority";
mongoose.connect(url, {
useNewUrlParser: true, useUnifiedTopology: true });
const userSchema = mongoose.Schema({
username:{
type:String,
unique:true,
required: true
},
email:{
type:String,
unique:true,
required:true
},
password:{
type:String,
required:true
}
})
const userModel = mongoose.model('user',userSchema)
module.exports = userModel