我想使用nodejs和mysql进行登录,但出现这样的错误:
undefined
undefined
SELECT * FROM user WHERE username = username AND password = password
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:455:11)
这是我的代码:
module.exports = (req, res) => {
let login = "";
res.send(htmlTemplate(login))
var username = req.body.username;
var password = req.body.password;
var sql = `SELECT * FROM user WHERE username = username AND password = password`;
console.log(username);
console.log(password);
console.log(sql);
if(username && password) {
connection.query('SELECT * FROM user WHERE username = username AND password = password', [username, password], function(error, results, fields){
if(results.length > 0){
req.session.loggedin = true;
req.session.username = username;
res.redirect('/dashboard');
} else {
res.send('Username and Password wrong!');
}
res.end();
});
} else {
res.send('please enter Username and Password');
res.end();
}
}
您能帮我解决这个问题吗?
谢谢。
答案 0 :(得分:0)
res.send
和res.json
结束了请求...因此您不必在之后添加请求。
if(username && password) {
connection.query('SELECT * FROM user WHERE username = username AND password = password', [username, password], function(error, results, fields){
if(results.length > 0){
req.session.loggedin = true;
req.session.username = username;
res.redirect('/dashboard');
} else {
res.send('Username and Password wrong!');
}
});
} else {
res.send('please enter Username and Password');
}
答案 1 :(得分:0)
问题是您已经添加了res.send(htmlTemplate(login))
,它结束了端点上收到的请求的响应。当此语句之后的方法流继续时,它会根据条件遇到res.redirect()
或res.send()
语句,并且该语句再次用于发送响应,但已经发送了响应,并引发错误。为了克服这个问题,请尝试分隔发送登录页面模板的路径,并分别处理登录用户背后的逻辑。