【发布时间】:2019-05-22 14:35:37
【问题描述】:
在我的登录/注册表单中,我使用了 jquery ajax 但它不起作用,当用户输入我的 mongo 数据库中不存在的错误信息时,它应该在我的 div 中添加用户未注册的错误消息(无需重新加载当然)但它不是发送我的错误消息,如res.send 方法(在空白页面中)这里是代码
app.post('/login',
async (req, res) => {
try {
const { username, password } = req.body;
const user = await User.findOne({ username, password }).select('-password').lean();
if (!user) {
res.status(500).send({error: "user is not registered"});
return;
}
req.session.user = user;
res.redirect('/dash')
return res.status(200).send('Session ID: ' + req.sessionID);
}
catch (error) {
res.status(500).send(error.message);
}
});
nodeJS 代码
<body>
<form action="/login" method="POST">
<input type="text" placeholder="username" name="username" id="username">
<input type="password" placeholder="pass" name="password" id="password">
<button type="submit" id="zaza">Login</button>
<div id="errMsg"></div>
<br/>
or <strong><a href="/reg">Sign Up</a></strong>
</form>
<script type="text/javascript">
$('#zaza').on('click', function(event) {
event.preventDefault();
const username = $('#username').val(), password = $('#password').val();
$.ajax({
type: 'POST',
data: { username: username, password: password },
url: 'http://localhost:8080/login',
success: function(sessionID) {
console.log(sessionID);
},
error: function(xhr, status, err) {
const errMsg = xhr.responseText; // Your error msg
$('#errMsg').html(errMsg);
}
});
});
</script>
ajax 代码
【问题讨论】: