通过 URL 将上下文传递到 NodeJS Express

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

我正在尝试使用 Node.js、Express 和 EJS 制作一个电子邮件验证系统。

目前,当用户注册时,服务器会生成一个链接,比如说

https://www.website.com/verify=foo/

然后将其发送到他们的电子邮件地址。如何使生成的链接定向到具有上下文

https://www.website.com/verify/
foo
,然后使用 POST 方法将其获取到
/verify
,以便我可以使用给定上下文执行代码?

javascript node.js express ejs
2个回答
0
投票

单击链接通常会引发 GET 请求。所以在你的服务器代码中你应该监听

get

app.get('/verify', function(req, res){
  res.send('foo: ' + req.query.foo);
});

请注意,在这种情况下,您的链接应包含

?
,如下所示:
https://www.website.com/verify/?foo=value


0
投票

我从你的问题中了解到,你想通过电子邮件向用户发送验证链接,并且你想在邮件中包含该链接。

这是一种可能的解决方案,其中包含使用 nodemailer 包的演示代码。

const express = require('express');
const nodemailer = require('nodemailer');  // Package used for sending mail to users
const app = express();

const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: '[email protected]',
        pass: 'test123' // This should be an App password generated from your Gmail account settings
    }
});

// Function to send verification email
function sendVerificationEmail(email, verificationLink) {
    // Email options
    const mailOptions = {
        from: '[email protected]',
        to: email,
        subject: 'Email Verification',
        html: `<p>Please click <a href="${verificationLink}">here</a> to verify your email address.</p>`
    };

    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            console.error('Error sending email:', error);
        } else {
            console.log('Email sent:', info.response);
        }
    });
}

// Register route
app.post('/register', (req, res) => {
    const { email } = req.body;

    // without token
    // const verification = `https://www.website.com/verify?value=foo`;

    // using token , first generate token based on the stored user information
    const verificationLink = `https://www.website.com/verify?token=foo`; // Modified to use a token in the query parameter
    // We want that when a user simply clicks on that link, technically they are essentially making a GET request. Therefore, it's better to pass it as a query parameter.


    // Send verification email
    sendVerificationEmail(email, verificationLink);

    res.send('Verification email sent successfully!');
});

app.get("/verify", (req, res) => {
    const { token } = req.query; // Fetching value from query parameter

    // Now this token can be verified against the one previously sent to the user

    // Generally, in the userModel, we create a field named isVerified which has a default value of 0. At the time of registration, when we create a user, we use JWT to generate a token containing user information in encrypted format.
    // Now, when a new user receives the verification email and clicks the link (in our case /verify?token=tokenValue), we decode the token and fetch user information from the database, updating the isVerified field.
    // Now, when the user tries to log in, we check the isVerified field in the database. If it is 1, the user can log in; otherwise, the user can't log in.

    console.log(token);
    res.send("Verified");
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});
© www.soinside.com 2019 - 2024. All rights reserved.