If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To implement user sign in, we need to perform the following steps:
/users/signin.POST requests on /users/signin.POST request to /users/signin.Here's an example implementation of the POST request to /users/signin:
javascriptCopy code
// server.js
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const session = require('express-session');
const User = require('./models/User');
// Set up session middleware
app.use(session({
secret: 'secret-key',
resave: false,
saveUninitialized: false
}));
// Set up body-parser middleware
app.use(express.urlencoded({ extended: true }));
// Connect to MongoDB
mongoose.connect('mongodb://localhost/myapp', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
});
// Define routes
// GET request to /users/signin
app.get('/users/signin', (req, res) => {
res.render('signin');
});
// POST request to /users/signin
app.post('/users/signin', async (req, res) => {
const { email, password } = req.body;
// Find user by email
const user = await User.findOne({ email });
if (!user) {
// User not found
return res.render('signin', { error: 'Invalid email or password' });
}
// Check if password is correct
if (user.password !== password) {
// Incorrect password
return res.render('signin', { error: 'Invalid email or password' });
}
// Save user ID in session
req.session.userId = user._id;
// Redirect to home page
res.redirect('/');
});
// Start server
app.listen(3000, () => {
console.log('Server started on port 3000');
});
In this example, we first extract the email and password from the req.body object. We then use User.findOne() to query the database for a user with the given email.
If a user is found, we check if the provided password matches the user's password. If the password is correct, we create a new session and store the user's ID in the session using req.session.userId.
If the email or password is incorrect, we render the signin view again with an error message.
Note that we're using async/await to handle the database query, which is an asynchronous operation. We're also using the express-session middleware to handle sessions, and we're setting the saveUninitialized option to false to prevent the middleware from creating empty sessions for every request.

When will I get my course?

Now, Your query was resolved.
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support
I am not able to access videos from second class and further. I have already completed first class