forget mot de passe api nodejs mongodb example
// Step 1: Install necessary packages
// Run these commands in your terminal or command prompt
// npm install express mongoose bcryptjs jsonwebtoken
// Step 2: Create a MongoDB schema for users
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
}
});
const User = mongoose.model('User', userSchema);
// Step 3: Create a route to handle password reset requests
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const router = express.Router();
router.post('/forgot-password', async (req, res) => {
const { email } = req.body;
try {
const user = await User.findOne({ email });
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
// Generate a reset token (you can customize token expiration and payload)
const resetToken = jwt.sign({ email }, 'your_secret_key', { expiresIn: '1h' });
// Send the reset token to the user via email or any desired method
// For this example, we'll just return it in the response
return res.status(200).json({ resetToken });
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Server Error' });
}
});
// Step 4: Set up your Express app and connect to MongoDB
const app = express();
app.use(express.json());
mongoose.connect('mongodb://localhost:27017/yourDBName', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
}).then(() => {
console.log('MongoDB Connected');
}).catch((err) => {
console.error('Error connecting to MongoDB', err);
});
app.use('/api', router);
// Step 5: Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
This code includes steps to set up a Node.js server using Express and MongoDB. It demonstrates creating a user schema, implementing a route for handling forgot password requests, establishing a connection to MongoDB, and starting the server on a specified port. You'll need to replace 'your_secret_key'
with an actual secret key for token signing, and 'mongodb://localhost:27017/yourDBName'
with your MongoDB connection string and database name.