OTP验证检查在Node.js中

huangapple go评论78阅读模式
英文:

OTP validation check in node js

问题

这是您的代码的翻译:

我创建了一个没有数据库的Web应用程序,它是一个简单的应用程序。如果用户想要登录到这个网站,用户需要通过他的邮件ID进行验证。当用户输入邮件ID后,系统会向用户的邮件发送一个4位数字的OTP。然后,用户需要使用该OTP进行登录。

问题:我无法调用端点来发送电子邮件,我收到404错误。

错误:未捕获的Promise中的SyntaxError:意外的标记'<',"<!DOCTYPE " ... 不是有效的JSON。

这是login.html文件:

<body>
	<form method="POST">
		<div class="container">
			<label for="email"><b>Email</b></label>
			<input type="email" placeholder="输入电子邮件" name="email" required>

			<button type="button" id="otp-btn">获取OTP</button>
		</div>

		<div class="container">
			<label for="otp"><b>OTP</b></label>
			<input type="text" placeholder="输入OTP" name="otp" required>
			<button id="loginBtn" type="submit" class="btn btn-primary" disabled>登录</button>
		</div>
	</form>

	<script>
		const otpBtn = document.getElementById('otp-btn');
		const loginBtn = document.getElementById('loginBtn');

		// 默认情况下禁用登录按钮
		loginBtn.disabled = true;

		// 为“获取OTP”按钮添加事件监听器
		otpBtn.addEventListener('click', async function(event) {
			event.preventDefault(); // 防止表单正常提交

			// 向服务器发送请求以发送OTP
			const email = document.querySelector('input[name="email"]').value;
			const response = await fetch('/generateOTP', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({ email })
			});
			const data = await response.json();

			// 根据响应更新UI
			if (data.success) {
				alert('已发送OTP到您的电子邮件!');
				loginBtn.disabled = false;
			} else {
				alert('无法发送OTP。请稍后重试。');
			}
		});

		// 为表单提交添加事件监听器
		document.querySelector('form').addEventListener('submit', async function(event) {
			event.preventDefault(); // 防止表单正常提交

			// 向服务器发送验证OTP的请求
			const email = document.querySelector('input[name="email"]').value;
			const otp = document.querySelector('input[name="otp"]').value;
			const response = await fetch('/verify-otp', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({ email, otp })
			});
			const data = await response.json();

			// 根据响应更新UI
			if (data.success) {
				alert('OTP验证成功!');
				window.location.href = '/MF.html';
			} else {
				alert('无效的OTP。请重试。');
			}
		});
	</script>
</body>

这是server.js文件的翻译:

const express = require("express");
const path = require("path");
const nodemailer = require("nodemailer");
const dotenv = require('dotenv');
dotenv.config();

const bodyParser = require('body-parser');

const app = express();
const port = 5000;

app.use(express.static(path.join(__dirname, 'public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get("/", (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'login.html'));
});

app.listen(port, () => {
  console.log(`服务器正在 http://localhost:${port} 上监听`);
});

const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
      user: "my@gmail.com",
      pass: "password"
  }
});

const otp = Math.floor(1000 + Math.random() * 9000);

app.post("/login", (req, res) => {
  const { otp } = req.body;
  // 验证OTP代码
  // 在这个示例中,我们仅出于演示目的使用硬编码值。
  // 在实际应用中,您应该将OTP与前一步骤中生成的OTP进行比较。
  
  if (otp === this.otpCode && otp != 0) {
    print("otp");
    print("otp" + otp);
    print(this.otpCode + "this otp");
    console.log(otp);
    console.log(this.otpCode);
    res.status(200).send({ message: '登录成功' });
    
  } else {
    res.status(401).send({ message: '无效的OTP' });
  }
});

app.post("/generateOTP", (req, res) => {
  const { email } = req.body;

  // 生成新的OTP代码并通过电子邮件发送
  this.otpCode = Math.floor(100000 + Math.random() * 900000);
  const mailOptions = {
    from: "my@gmail.com",
    to: email,
    subject: "登录OTP",
    text: `您的OTP代码是 ${this.otpCode}。`,
  };

  transporter.sendMail(mailOptions, (error, _info) => {
    if (error) {
      console.error('发送电子邮件时出错:', error);
      res.status(500).send({ message: '无法发送OTP' });
    } else {
      console.log('已发送OTP:', this.otpCode);
      res.status(200).send({ message: 'OTP已成功发送' });
    }
  });
});

请注意,我已将HTML和JavaScript代码分别翻译,并在代码中使用了合适的标记。希望这有助于您理解代码的功能和结构。

英文:

I created an web application where there is no data base it is an simple application. If user want to login to this website user need to verify through his mailID, When user entered mailid an 4 digit OTP will be sent to user mail. After that he need to verify with that to login.

Prob: I am unable to call endpoint to send email I am getting 404 error.

error: Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON.

This is login.html file:

&lt;body&gt;
&lt;form method=&quot;POST&quot;&gt;
&lt;div class=&quot;container&quot;&gt;
&lt;label for=&quot;email&quot;&gt;&lt;b&gt;Email&lt;/b&gt;&lt;/label&gt;
&lt;input type=&quot;email&quot; placeholder=&quot;Enter Email&quot; name=&quot;email&quot; required&gt;
&lt;button type=&quot;button&quot; id=&quot;otp-btn&quot;&gt;Get OTP&lt;/button&gt;
&lt;/div&gt;
&lt;div class=&quot;container&quot;&gt;
&lt;label for=&quot;otp&quot;&gt;&lt;b&gt;OTP&lt;/b&gt;&lt;/label&gt;
&lt;input type=&quot;text&quot; placeholder=&quot;Enter OTP&quot; name=&quot;otp&quot; required&gt;
&lt;button id=&quot;loginBtn&quot; type=&quot;submit&quot; class=&quot;btn btn-primary&quot; disabled&gt;Login&lt;/button&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;script&gt;
const otpBtn = document.getElementById(&#39;otp-btn&#39;);
const loginBtn = document.getElementById(&#39;loginBtn&#39;);
// Disable the login button by default
loginBtn.disabled = true;
// Add event listener for &quot;Get OTP&quot; button
otpBtn.addEventListener(&#39;click&#39;, async function(event) {
event.preventDefault(); // Prevent form from submitting normally
// Send request to server to send OTP
const email = document.querySelector(&#39;input[name=&quot;email&quot;]&#39;).value;
const response = await fetch(&#39;/generateOTP&#39;, {
method: &#39;POST&#39;,
headers: {
&#39;Content-Type&#39;: &#39;application/json&#39;
},
body: JSON.stringify({ email })
});
const data = await response.json();
// Update UI based on response
if (data.success) {
alert(&#39;OTP sent to your email!&#39;);
loginBtn.disabled = false;
} else {
alert(&#39;Failed to send OTP. Please try again later.&#39;);
}
});
// Add event listener for form submission
document.querySelector(&#39;form&#39;).addEventListener(&#39;submit&#39;, async function(event) {
event.preventDefault(); // Prevent form from submitting normally
// Send request to server to validate OTP
const email = document.querySelector(&#39;input[name=&quot;email&quot;]&#39;).value;
const otp = document.querySelector(&#39;input[name=&quot;otp&quot;]&#39;).value;
const response = await fetch(&#39;/verify-otp&#39;, {
method: &#39;POST&#39;,
headers: {
&#39;Content-Type&#39;: &#39;application/json&#39;
},
body: JSON.stringify({ email, otp })
});
const data = await response.json();
// Update UI based on response
if (data.success) {
alert(&#39;OTP validation successful!&#39;);
window.location.href = &#39;/MF.html&#39;;
} else {
alert(&#39;Invalid OTP. Please try again.&#39;);
}
});
&lt;/script&gt;
&lt;/body&gt;

This is server.js file :

const express = require(&quot;express&quot;);
const path = require(&quot;path&quot;);
const nodemailer = require(&quot;nodemailer&quot;);
const dotenv = require(&#39;dotenv&#39;);
dotenv.config();
const bodyParser = require(&#39;body-parser&#39;);
const app = express();
const port = 5000;
app.use(express.static(path.join(__dirname, &#39;public&#39;)));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get(&quot;/&quot;, (req, res) =&gt; {
res.sendFile(path.join(__dirname, &#39;public&#39;, &#39;login.html&#39;));
});
app.listen(port, () =&gt; {
console.log(`Server listening at http://localhost:${port}`);
});
const transporter = nodemailer.createTransport({
service: &#39;gmail&#39;,
auth: {
user: &quot;my@gmail.com&quot;,
pass: &quot;password&quot;
}
});
const otp = Math.floor(1000 + Math.random() * 9000);
app.post(&quot;/login&quot;, (req, res) =&gt; {
const { otp } = req.body;
// Verify the OTP code
// In this example, we are using a hardcoded value for demonstration purposes only.
// In a real application, you should compare the OTP to the one generated in the previous step.
if (otp === this.otpCode &amp;&amp; otp!=0) {
print(&quot;otp&quot;);
print(&quot;otp&quot;+otp);
print(this.otpCode+&quot;this otp&quot;);
console.log(otp);
console.log(this.otpCode);
res.status(200).send({ message: &#39;Login successful&#39; });
} else {
res.status(401).send({ message: &#39;Invalid OTP&#39; });
}
});
app.post(&quot;/generateOTP&quot;, (req, res) =&gt; {
const { email } = req.body;
// Generate a new OTP code and send it via email
this.otpCode = Math.floor(100000 + Math.random() * 900000);
const mailOptions = {
from: &quot;my@gmail.com&quot;,
to: email,
subject: &quot;LogIn OTP&quot;,
text: `Your OTP code is ${this.otpCode}.`,
};
transporter.sendMail(mailOptions, (error, _info) =&gt; {
if (error) {
console.error(&#39;Error sending email: &#39;, error);
res.status(500).send({ message: &#39;Failed to send OTP&#39; });
} else {
console.log(&#39;OTP sent: &#39;, this.otpCode);
res.status(200).send({ message: &#39;OTP sent successfully&#39; });
}
});
});

答案1

得分: 1

您需要在您的服务器上创建/verify-otp端点。

编辑

所根据您的代码,客户端正在调用/verify-otp端点来执行OTP验证。然而,在您的server.js文件中,该端点并不存在。但我注意到您在/login端点上执行OTP验证。所以将app.post("/login")更改为app.post("/verify-otp")应该解决问题。

以下是您提供的代码的翻译部分:

const express = require("express");
const path = require("path");
const nodemailer = require("nodemailer");
const dotenv = require('dotenv');
dotenv.config();

const bodyParser = require('body-parser');

const app = express();
const port = 5000;

app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json();

app.get("/", (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});

const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
      user: "my@gmail.com",
      pass: "password"
  }
});

const otp = Math.floor(1000 + Math.random() * 9000);

app.post("/verify-otp", (req, res) => {
  const { otp } = req.body;
  // Verify the OTP code
  // In this example, we are using a hardcoded value for demonstration purposes only.
  // In a real application, you should compare the OTP to the one generated in the previous step.
  
  if (otp === this.otpCode && otp != 0) {
    print("otp");
    print("otp" + otp);
    print(this.otpCode + "this otp");
    console.log(otp);
    console.log(this.otpCode);
    res.status(200).send({ message: 'Login successful' });
    
  } else {
    res.status(401).send({ message: 'Invalid OTP' });
  }
});

app.post("/generateOTP", (req, res) => {
  const { email } = req.body;

  // Generate a new OTP code and send it via email
  this.otpCode = Math.floor(100000 + Math.random() * 900000);
  const mailOptions = {
    from: "my@gmail.com",
    to: email,
    subject: "LogIn OTP",
    text: `Your OTP code is ${this.otpCode}.`,
  };

  transporter.sendMail(mailOptions, (error, _info) => {
    if (error) {
      console.error('Error sending email: ', error);
      res.status(500).send({ message: 'Failed to send OTP' });
    } else {
      console.log('OTP sent: ', this.otpCode);
      res.status(200).send({ message: 'OTP sent successfully' });
    }
  });
});
<html>
    <head>
        <title>Abcd</title>
    </head>
    <body>
        <form method="POST">
            <div class="container">
                <label for="email"><b>Email</b></label>
                <input type="email" placeholder="Enter Email" name="email" required>

                <button type="button" id="otp-btn">Get OTP</button>
            </div>

            <div class="container">
                <label for="otp"><b>OTP</b></label>
                <input type="text" placeholder="Enter OTP" name="otp" required>
                <button id="loginBtn" type="submit" class="btn btn-primary" disabled>Login</button>
            </div>
        </form>

        <script>
            const otpBtn = document.getElementById('otp-btn');
            const loginBtn = document.getElementById('loginBtn');

            // Disable the login button by default
            loginBtn.disabled = true;

            // Add event listener for "Get OTP" button
            otpBtn.addEventListener('click', async function(event) {
                event.preventDefault(); // Prevent form from submitting normally

                // Send request to server to send OTP
                const email = document.querySelector('input[name="email"]').value;
                const response = await fetch('/generateOTP', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ email })
                });
                const data = await response.json();

                // Update UI based on response
                if (data.success) {
                    alert('OTP sent to your email!');
                    loginBtn.disabled = false;
                } else {
                    alert('Failed to send OTP. Please try again later.');
                }
            });

            // Add event listener for form submission
            document.querySelector('form').addEventListener('submit', async function(event) {
                event.preventDefault(); // Prevent form from submitting normally

                // Send request to server to validate OTP
                const email = document.querySelector('input[name="email"]').value;
                const otp = document.querySelector('input[name="otp"]').value;
                const response = await fetch('/verify-otp', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ email, otp })
                });
                const data = await response.json();

                // Update UI based on response
                if (data.success) {
                    alert('OTP validation successful!');
                    window.location.href = '/MF.html';
                } else {
                    alert('Invalid OTP. Please try again.');
                }
            });
        </script>
    </body>
</html>

希望这能帮助您创建/verify-otp端点。

英文:

You need to create the /verify-otp endpoint on your server.
EDIT
So based on your code, on client side you are calling the /verify-otp endpoint to perform otp verification. However on your server.js, that endpoint doesn't exist. However i have noticed that you are performing otp verification in your '/login' endpoint on your server.js. So changing app.post(&quot;/login&quot;) to app.post(&quot;/verify-otp&quot;) should fix.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const express = require(&quot;express&quot;);
const path = require(&quot;path&quot;);
const nodemailer = require(&quot;nodemailer&quot;);
const dotenv = require(&#39;dotenv&#39;);
dotenv.config();
const bodyParser = require(&#39;body-parser&#39;);
const app = express();
const port = 5000;
app.use(express.static(path.join(__dirname, &#39;public&#39;)));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get(&quot;/&quot;, (req, res) =&gt; {
res.sendFile(path.join(__dirname, &#39;public&#39;, &#39;index.html&#39;));
});
app.listen(port, () =&gt; {
console.log(`Server listening at http://localhost:${port}`);
});
const transporter = nodemailer.createTransport({
service: &#39;gmail&#39;,
auth: {
user: &quot;my@gmail.com&quot;,
pass: &quot;password&quot;
}
});
const otp = Math.floor(1000 + Math.random() * 9000);
app.post(&quot;/verify-otp&quot;, (req, res) =&gt; {
const { otp } = req.body;
// Verify the OTP code
// In this example, we are using a hardcoded value for demonstration purposes only.
// In a real application, you should compare the OTP to the one generated in the previous step.
if (otp === this.otpCode &amp;&amp; otp!=0) {
print(&quot;otp&quot;);
print(&quot;otp&quot;+otp);
print(this.otpCode+&quot;this otp&quot;);
console.log(otp);
console.log(this.otpCode);
res.status(200).send({ message: &#39;Login successful&#39; });
} else {
res.status(401).send({ message: &#39;Invalid OTP&#39; });
}
});
app.post(&quot;/generateOTP&quot;, (req, res) =&gt; {
const { email } = req.body;
// Generate a new OTP code and send it via email
this.otpCode = Math.floor(100000 + Math.random() * 900000);
const mailOptions = {
from: &quot;my@gmail.com&quot;,
to: email,
subject: &quot;LogIn OTP&quot;,
text: `Your OTP code is ${this.otpCode}.`,
};
transporter.sendMail(mailOptions, (error, _info) =&gt; {
if (error) {
console.error(&#39;Error sending email: &#39;, error);
res.status(500).send({ message: &#39;Failed to send OTP&#39; });
} else {
console.log(&#39;OTP sent: &#39;, this.otpCode);
res.status(200).send({ message: &#39;OTP sent successfully&#39; });
}
});
});

<!-- language: lang-html -->

&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Abcd&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;form method=&quot;POST&quot;&gt;
&lt;div class=&quot;container&quot;&gt;
&lt;label for=&quot;email&quot;&gt;&lt;b&gt;Email&lt;/b&gt;&lt;/label&gt;
&lt;input type=&quot;email&quot; placeholder=&quot;Enter Email&quot; name=&quot;email&quot; required&gt;
&lt;button type=&quot;button&quot; id=&quot;otp-btn&quot;&gt;Get OTP&lt;/button&gt;
&lt;/div&gt;
&lt;div class=&quot;container&quot;&gt;
&lt;label for=&quot;otp&quot;&gt;&lt;b&gt;OTP&lt;/b&gt;&lt;/label&gt;
&lt;input type=&quot;text&quot; placeholder=&quot;Enter OTP&quot; name=&quot;otp&quot; required&gt;
&lt;button id=&quot;loginBtn&quot; type=&quot;submit&quot; class=&quot;btn btn-primary&quot; disabled&gt;Login&lt;/button&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;script&gt;
const otpBtn = document.getElementById(&#39;otp-btn&#39;);
const loginBtn = document.getElementById(&#39;loginBtn&#39;);
// Disable the login button by default
loginBtn.disabled = true;
// Add event listener for &quot;Get OTP&quot; button
otpBtn.addEventListener(&#39;click&#39;, async function(event) {
event.preventDefault(); // Prevent form from submitting normally
// Send request to server to send OTP
const email = document.querySelector(&#39;input[name=&quot;email&quot;]&#39;).value;
const response = await fetch(&#39;/generateOTP&#39;, {
method: &#39;POST&#39;,
headers: {
&#39;Content-Type&#39;: &#39;application/json&#39;
},
body: JSON.stringify({ email })
});
const data = await response.json();
// Update UI based on response
if (data.success) {
alert(&#39;OTP sent to your email!&#39;);
loginBtn.disabled = false;
} else {
alert(&#39;Failed to send OTP. Please try again later.&#39;);
}
});
// Add event listener for form submission
document.querySelector(&#39;form&#39;).addEventListener(&#39;submit&#39;, async function(event) {
event.preventDefault(); // Prevent form from submitting normally
// Send request to server to validate OTP
const email = document.querySelector(&#39;input[name=&quot;email&quot;]&#39;).value;
const otp = document.querySelector(&#39;input[name=&quot;otp&quot;]&#39;).value;
const response = await fetch(&#39;/verify-otp&#39;, {
method: &#39;POST&#39;,
headers: {
&#39;Content-Type&#39;: &#39;application/json&#39;
},
body: JSON.stringify({ email, otp })
});
const data = await response.json();
// Update UI based on response
if (data.success) {
alert(&#39;OTP validation successful!&#39;);
window.location.href = &#39;/MF.html&#39;;
} else {
alert(&#39;Invalid OTP. Please try again.&#39;);
}
});
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月4日 10:01:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75924966.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定