我试图理解为什么在函数外部发送ajax响应,但不在函数内部。响应对象可在函数内访问,但不会发送实际响应。什么会导致这种行为?
app.post('/login', urlencodedParser, function(req, res){
if (!req.body) return res.sendStatus(400);
var password = JSON.stringify(req.body.password);
var username = JSON.stringify(req.body.username);
//res.send('Invalid'); //This sends a response
login.login(username, password,function(err,content) {
if(err){res.send('Invalid');} //This does not send a response
else {
agent_valid = content[0].valid;
if (agent_valid === 0)
{
console.log(agent_valid); //agent_valid is appearing as 1 or 0
console.log(res); //res exists and is written to console
res.send('Invalid'); //This does not send a response
}
if (agent_valid === 1)
{
res.send('Valid'); //This does not send a response
}
}
});
});
这是发送帖子请求的javascript:
ajaxRequest.send(JSON.stringify({username:username, password:password}));
ajaxRequest.onreadystatechange = function() {
if(this.readyState == 4 && this.responseText == 'Invalid') {
window.alert(this.responseText)
};
if(this.readyState == 4 && this.responseText !='Invalid'){
window.alert(this.responseText)
};
}