Javascript 即使if语句条件有效,Else语句也会执行
我正在使用谷歌云功能验证我的OTP身份验证,还使用Firebase数据库将代码保存在数据库中 我的问题是,即使满足If语句条件,它也总是执行else语句。我正在将firebase数据库中的代码和codeValid与用户输入进行比较。因此,我的用户输入对代码和codevalid都很满意,但它总是移到else语句。我不知道为什么 这是我的密码Javascript 即使if语句条件有效,Else语句也会执行,javascript,firebase,google-cloud-platform,Javascript,Firebase,Google Cloud Platform,我正在使用谷歌云功能验证我的OTP身份验证,还使用Firebase数据库将代码保存在数据库中 我的问题是,即使满足If语句条件,它也总是执行else语句。我正在将firebase数据库中的代码和codeValid与用户输入进行比较。因此,我的用户输入对代码和codevalid都很满意,但它总是移到else语句。我不知道为什么 这是我的密码 const admin = require('firebase-admin'); module.exports = function(req, res) {
const admin = require('firebase-admin');
module.exports = function(req, res) {
if(!req.body.phone || !req.body.code) {
return res.status(422).send({error: 'Phone and Code Must be
Provided'});
}
const phone = String(req.body.phone).replace(/[^\d]/g, '');
const code = parseInt(req.body.code);
return admin.auth().getUser(phone)
.then(() => {
const ref = admin.database().ref('users/'+ phone);
return ref.on('value', snapshot => {
ref.off();
const user = snapshot.val();
if (user.code === code && user.codeValid === true) {
ref.update({ codeValid: false });
admin.auth().createCustomToken(phone)
.then(token => res.send({ token: token }))
.catch((err)=> res.status(422).send({ error:err }));
}
else {
return res.status(422).send({ error: 'Code Not Valid' });
}
});
})
.catch((err)=> res.status(422).send({ error:err }) )
}
所以,无论我输入什么,我总是得到“代码无效”。我还用firebase数据库交叉检查了所有值,所有值都匹配。但是找不到它发生的原因。将此添加到您的
if条件
之上,并检查您的陈述是否真实。我认为您的数据类型可能是不同的,例如user.code
和code
。因此,您还应该使用=
或解析您的值来测试它
// values and datatypes are equal
if (user.code === code) {
console.log('user.code === code');
}
// values and datatypes are equal
if (user.codeValid === true) {
console.log('user.codeValid === codeValid');
}
// values are equal
if (user.code == code) {
console.log('user.code == code');
}
// values are equal
if (user.codeValid == true) {
console.log('user.codeValid == codeValid');
}
有关=
和===
区别的更多信息,请查看以下答案:
是否为
user.code==code&&user.code有效===true
始终为true
?是的,它应该始终为true,以便用户输入的代码与数据库存储的代码相等。我已经将codeValid设置为true(最初),当这个函数运行时,它将使用parseInt(user.code)==code&&user.codeValid==true更新codeValid为falseTry。为了找到发生了什么,我会尝试使用user.code
,编写一个长消息错误(临时或非临时;我还没有阅读所有代码),code
和user.codeValid
。我希望它能帮助你。当运行else块时,可能并不总是这样。谢谢你的话,实际上user.code和code是不同类型的!这就是问题所在。现在清除