代码应该接收密码并检查密码是否与数据库中的密码匹配并返回结果。相反,无论我尝试什么,它都会给出相同的错误。
Express JS:
app.post('/', (req, res) => {
console.log('Received POST Request!')
const { Username, Password } = req.body;
console.log('Received Username:', Username);
console.log('Received Password:', Password);
res.send('Received Username: ' + Username);
pool.query('SELECT * FROM user WHERE username = ? LIMIT 1', [Username], (error, results, fields) => {
if (error) {
console.error(error);
//return res.status(500).send('Internal Server Error');
} else {
if (results.length === 0) {
//return res.status(404).send('User not found');
} else {
const user = results[0];
const storedPassword = user.password;
if (Password === storedPassword) {
//return res.status(200).send('Password Matched');
console.log('Passwords matched')
} else {
return res.status(401).send('Incorrect Password');
console.log('Passwords didnt match')
}
}
}
});
});`
我重写了代码几次,我评论了一些回复以查看问题是否仍然存在。它识别出密码不同,但返回结果时出错。
当您调用
res.send(...)
时,express会将响应分派回客户端,包括所有先前设置的标头和分配的状态代码。发送响应后,与客户端的连接将关闭。 查看 response.js
了解其幕后工作原理。
当你的路线被执行时,你几乎立即运行这条线:
res.send('Received Username: ' + Username);
这是将给定消息作为您的响应发送给客户端(默认为
200 OK
响应代码),并关闭响应。任何进一步的 .send
调用都会被忽略。
如果您想解决问题,只需删除此行(并取消注释其他
res.status(..).send(..)
调用)。