英文:
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:
<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>
This is server.js file :
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(`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("/login", (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' });
}
});
});
答案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("/login")
to app.post("/verify-otp")
should fix.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-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', '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' });
}
});
});
<!-- language: lang-html -->
<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>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论