我正在编写一些Node JS API进行登录。我已经编写了逻辑,但是在发回响应时遇到问题。这是我的代码:
app.post('/API/login', (request, response) => {
model.findOne({ email: request.body.email }, (err, result) => {
if (err) throw err;
if (result) {
bcrypt.compare(request.body.password, result.password, function (error, hash) {
if (error) throw err;
if (hash) {
request.session.logged = true;
request.session._id = result._id;
response.send(result._id);
}
else {
response.send('Incorrect Username and/or Password!');
}
})
} else {
response.send('Incorrect Username and/or Password!');
}
response.end();
})
});
但是,我遇到了一个问题。我不断收到以下错误:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (node_modules\express\lib\response.js:775:10)
at ServerResponse.json (node_modules\express\lib\response.js:268:10)
at ServerResponse.send node_modules\express\lib\response.js:162:21
at login.js:73:34
at node_modules\bcryptjs\dist\bcrypt.js:297:21
at node_modules\bcryptjs\dist\bcrypt.js:1353:21
at Immediate.next (node_modules\bcryptjs\dist\bcrypt.js:1233:21)
at runCallback (timers.js:705:18)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)
我不确定是什么导致了此问题。
答案 0 :(得分:1)
您已经用response.end()
回答后,尝试使用response.send(...)
发送回复
您可以删除response.end()
声明:
app.post('/API/login', (request, response) => {
model.findOne({ email: request.body.email }, (err, result) => {
if (err) throw err;
if (result) {
bcrypt.compare(request.body.password, result.password, function (error, hash) {
if (error) throw err;
if (hash) {
request.session.logged = true;
request.session._id = result._id;
response.send(result._id);
}
else {
response.send('Incorrect Username and/or Password!');
}
})
} else {
response.send('Incorrect Username and/or Password!');
}
})
});