我正在创建一个Express终结点,用于验证用户名/密码是否在我的数据库(json文件)中
router.post('/login', (req, res) => {
let userData = req.body;
if (validateEmailAndPassword(userData.username, userData.password) {
res.send(userData);
} else {
res.status(401).send({ error: "Username/Password combination is incorrect." });
}
})
const validateEmailAndPassword = (username, password) => {
let validCreds = false;
fs.readFile('db/users.json', 'utf8', (err, data) => {
if (data) {
const stream = JSON.parse(data);
const usersFound = stream.filter(info => {
if (info.username === username && info.password ===password) { return true; }
})
if (usersFound.length >= 1) { validCreds = true; }
return validCreds;
} else {
throw Error(err);
}
})
}
第一个代码块第3行中的'validateEmailAndPassword(userData.username,userData.password)'在if条件下返回'undefined',因为它是异步的。
同步解析'validateEmailAndPassword(userData.username,userData.password)'的最佳方法是什么,以便在不使用readFileSync的情况下获得true / false值?
谢谢!
答案 0 :(得分:2)
使用async
await
和promises
router.post('/login', async(req, res) => {
let userData = req.body;
if (await validateEmailAndPassword(userData.username, userData.password)) {
res.send(userData);
} else {
res.status(401).send({ error: "Username/Password combination is incorrect." });
}
})
const validateEmailAndPassword = (username, password) => {
let validCreds = false;
return new Promise(resolve => {
fs.readFile('db/users.json', 'utf8', (err, data) => {
if (data) {
const stream = JSON.parse(data);
const usersFound = stream.filter(info => {
if (info.username === username && info.password ===password) { return true; }
})
if (usersFound.length >= 1) { validCreds = true; }
resolve(validCreds);
return validCreds;
} else {
throw Error(err);
}
})
})
}
tada
答案 1 :(得分:0)
要扩展@Estradiaz答案...
听起来您想同步使用它,所以您可以使其同步而不是使其异步并等待它:
readFile-> readFileSync
const validateEmailAndPassword = (username, password) => {
let validCreds = false;
var data = fs.readFileSync('db/users.json', 'utf8');
if (data) {
const stream = JSON.parse(data);
const usersFound = stream.filter(info => {
if (info.username === username && info.password === password)
return true;
});
if (usersFound.length >= 1)
validCreds = true;
return validCreds;
} else {
throw Error(err);
}
}