ReactJS、NodeJS、MongoDB、后端

问题描述 投票:0回答:1

在index.js中,

const express = require("express")
const mongoose = require("mongoose")
const cors = require("cors")
const CustomerModel = require('./models/Customer')




const app = express()
app.use(express.json())
app.use(cors())

mongoose.connect("mongodb://localhost:27017/customer")

app.post("/login", (req, res) => {
    const {email, password} = req.body
    CustomerModel.findOne({email: email})
    .then(user => {
        if(user) {
            if(user.password === password) {
                res.json("Success")
            } else {
                res.json("the password is incorrect")
            }
        } else {
            res.json("No record existed")
        }
    })
})


app.post('/register', (req, res) => {
    CustomerModel.create(req.body)
    .then(customers => res.json(customers))
    .catch(err => res.json(err))
})

app.listen(3001, () => {
    console.log("server is running")
}) 

/////////////////

在 customer.js 中,

const mongoose = require("mongoose")

const CustomerSchema = new mongoose.Schema({
    name: String,
    email: String,
    password: String,

})

const CustomerModel = mongoose.model("customer", CustomerSchema)
module.exports = CustomerModel

//////////////////

帮我修改这个代码,以便我可以进行电子邮件验证, 注意:我已经安装了nodemailer、crypto、dotenv以及电子邮件验证所需的所有东西。

请加上一些注释,以修改我的前端,我应该添加什么?我放置了很多代码,以便您可以修改它来进行电子邮件验证。所以请回答这个问题,我正在学习 React 和 Node。顺便说一句,这是后端,因此用户界面提到,如果我需要修改我的前端,请添加详细信息。您可以使用 OTP 或使用链接的电子邮件验证来修改它。

node.js mongodb mongoose
1个回答
0
投票

请尝试以下解决方案...

首先,您需要使用

.env
文件设置环境变量..

EMAIL_USER = [email protected]
EMAIL_PASS = your-email-password
EMAIL_HOST = smtp.your-email-provider.com
EMAIL_PORT = 587
JWT_SECRET = your-secret-key

index.js:

const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const crypto = require("crypto");
const nodemailer = require("nodemailer");
const dotenv = require("dotenv");
const CustomerModel = require('./models/Customer');

dotenv.config();

const app = express();
app.use(express.json());
app.use(cors());

mongoose.connect("mongodb://localhost:27017/customer", { useNewUrlParser: true, useUnifiedTopology: true });

const transporter = nodemailer.createTransport({
    host: process.env.EMAIL_HOST,
    port: process.env.EMAIL_PORT,
    secure: false, // true for 465, false for other ports
    auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS
    }
});

app.post("/register", (req, res) => {
    const { name, email, password } = req.body;
    const verificationToken = crypto.randomBytes(20).toString('hex');
    
    const newCustomer = new CustomerModel({
        name,
        email,
        password,
        verificationToken,
        isVerified: false
    });
    
    newCustomer.save()
        .then(customer => {
            const verificationLink = `http://localhost:3000/verify-email?token=${verificationToken}`;

            const mailOptions = {
                from: process.env.EMAIL_USER,
                to: customer.email,
                subject: 'Email Verification',
                text: `Please verify your email by clicking the following link: ${verificationLink}`
            };

            transporter.sendMail(mailOptions, (error, info) => {
                if (error) {
                    return res.status(500).json({ error: 'Failed to send verification email' });
                }
                res.status(200).json({ message: 'Registration successful, please verify your email' });
            });
        })
        .catch(err => res.status(500).json(err));
});

app.get("/verify-email", (req, res) => {
    const { token } = req.query;
    
    CustomerModel.findOne({ verificationToken: token })
        .then(user => {
            if (!user) {
                return res.status(400).json({ error: 'Invalid or expired token' });
            }
            
            user.isVerified = true;
            user.verificationToken = null;
            user.save()
                .then(() => res.status(200).json({ message: 'Email verified successfully' }))
                .catch(err => res.status(500).json(err));
        })
        .catch(err => res.status(500).json(err));
});

app.post("/login", (req, res) => {
    const { email, password } = req.body;
    CustomerModel.findOne({ email: email })
        .then(user => {
            if (user) {
                if (user.password === password) {
                    if (user.isVerified) {
                        res.json("Success");
                    } else {
                        res.json("Please verify your email first");
                    }
                } else {
                    res.json("The password is incorrect");
                }
            } else {
                res.json("No record existed");
            }
        })
        .catch(err => res.status(500).json(err));
});

app.listen(3001, () => {
    console.log("Server is running on port 3001");
});

模型/Customer.js:

const mongoose = require("mongoose");

const CustomerSchema = new mongoose.Schema({
    name: String,
    email: String,
    password: String,
    verificationToken: String,
    isVerified: { type: Boolean, default: false }
});

const CustomerModel = mongoose.model("Customer", CustomerSchema);
module.exports = CustomerModel;

所以,你还需要更改前端部分代码。

© www.soinside.com 2019 - 2024. All rights reserved.