我正在制作带有登录屏幕等的基本网站。
目前,我正在注册页面上,该页面对用户的验证很少,例如“电子邮件存在”,“确认电子邮件已发送”等。
实现此目的或您个人喜好的最佳方法是什么?
下面,我将代码包含在我尝试实现此方法的示例中。
我具有从服务器端到控制台的基本日志记录,其中包含以下代码段。
app.post("/register-email", async (req, response) => {
let emailAvailabilitylResponse = "";
var Email = req.body.email;
await sql.connect(config);
var request = new sql.Request();
request.input("Email", sql.VarChar, Email);
const result = await request.execute("dbo.CheckEmailExists");
if (result.recordsets[0].length > 0) {
emailAvailabilitylResponse = "This email already exists"; // this works on console
console.info(emailAvailabilitylResponse);
console.log(req.body);
} else {
console.log({ Email });
emailAvailabilitylResponse = "An email has been sent to your inbox"; //this work on console
console.info(emailAvailabilitylResponse);
const token = jwt.sign({ user: Email }, "register-email", {
expiresIn: 3600000
});
response.status(200).json({
ok: true,
user: Email,
jwt: token,
emailAvailability: emailAvailabilityResponse
});
我试图将此信息传递回我的json文件中,但是当尝试向用户显示此信息时仍然无法正常工作。
这是我的代码的客户端。这是一个句柄提交,一旦单击注册表的按钮,就会触发该提交。
handleSubmit(e) {
e.preventDefault();
const EmailAvailbiltly = "";
if (this.state.email.length < 8) {
alert(`please enter email correctly `); //this works and displays as alert
} else {
const data = { email: this.state.email };
console.log(data);
fetch("/register-email", {
method: "POST", // or 'PUT'
headers: {
Accept: "application/json,",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => {
console.log("response before it is broken down " + response);
return response.json();
})
.then(({ jwt, user, emailAvailabilityResponse }) => {
console.log(
"After it is broken down",
jwt,
user,
emailAvailabilityResponse
);
EmailAvailbiltly = emailAvailabilityResponse;
});
alert(`"reponse 2" ${EmailAvailbiltly}`); // I cannot get the an alert with this response.
console.log(EmailAvailbiltly); //This should be the messages contained in
//server.js
console.log(`"reponse 2" ${EmailAvailbiltly}`);
}
}
编辑
根据请求的控制台信息
如果存在电子邮件
[0] Server running on port 5000
[0] This email already exists
[0] { email: 'testuser@gmail.com' }
如果电子邮件不存在
[0] { Email: 'testing@gmail.com' }
[0] An email has been sent to your inbox
但这是纯粹的控制台,而我希望它可以是前端
答案 0 :(得分:0)
为解决这个问题,我在两个if语句中创建了一条错误消息,并将其与json一起传递回去。之后,我只是从前端调用了错误消息。
伪代码
error message
if(a statement)
error message = "whatever it needs to be"
res.sendjson(with error message)
else(a statement)
error message = "something different"
res.sendjson(with error message)
然后在我的客户端,我只是提取了错误消息,然后将其放入警报中。
我希望这对某人有帮助:)