If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To implement user sign up functionality in an Express.js app, we need to follow these steps:
POST
route for /signup
in the server.js file.bcrypt
module to hash the password before storing it in the database.POST
route for /signup
, retrieve the email and password from the request body.bcrypt
and save the new user in the database using the User model.user
property to the req.session
object.Here's an example implementation of these steps:
phpCopy code
// server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt');
const session = require('express-session');
const app = express();
mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session({
secret: 'myapp',
resave: false,
saveUninitialized: true
}));
const userSchema = new mongoose.Schema({
email: { type: String, required: true },
password: { type: String, required: true }
});
const User = mongoose.model('User', userSchema);
app.get('/', (req, res) => {
res.render('index');
});
app.post('/signup', async (req, res) => {
const { email, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const user = new User({
email,
password: hashedPassword
});
await user.save();
req.session.user = user;
res.redirect('/');
});
app.listen(3000, () => console.log('Server started on port 3000'));
In this example, we've used the bcrypt
module to hash the password before storing it in the database. We've also used the express-session
middleware to create a session for the user. Finally, we've added a POST
route for /signup
that saves the new user to the database and creates a session for them.
When will I get my course?
Now, Your query was resolved.
Quick answers to common questions about our courses, quizzes, and learning platform
I am not able to access videos from second class and further. I have already completed first class