Вы не можете отправить перенаправление и статус с сообщением одновременно.
Лучше определить, является ли запрос ajax, json или нет, и в зависимости от требований ответьте правильным ответом.
Так что здесь исправление:
1) Исправить код на стороне сервера:
app.post('/login', async (req, res) => {
try {
const {username, password} = req.body;
const user = await User.findOne({username, password}).select('-password').lean();
if (!user) {
return res.status(404).send({
message: 'user is not registered'
});
}
req.session.user = user;
const redirectTo = '/dash';
if (
req.is('json') // request content type is json
|| // or
req.xhr // is ajax
) {
// respond with json response
return res.status(200).status({redirectTo});
}
// not ajax request
// then respond redirect header
res.redirect(redirectTo);
}
catch (error) {
res.status(500).send({
message: error.message
});
}
});
2) Исправить код на стороне клиента:
<form id="login" action="/login" method="POST">
<label>
Username:
<input type="text" name="username" value="">
</label>
<label>
Password:
<input type="password" name="password" value="" autocomplete="off">
</label>
<button type="submit">Login</button>
<br/>
<div class="error"></div>
</form>
<script type="text/javascript">
$(function() {
var $loginForm = $('form#login');
// handle form submit event
$loginForm.on('submit', function(e) {
e.preventDefault(); // prevent browser doing default post
$.ajax({
type: $loginForm.attr('method'), // get method from form tag
url: $loginForm.attr('action'), // get action url from form tag
data: $loginForm.serialize(), // sending url-encoded string from fields
// something went wrong
error: function(xhr, textStatus, error) {
try {
var response = JSON.parse(xhr.responseText);
if (response.message) { // if json response has message field
$loginForm.find('.error:first').html(response.message);
}
}
catch (error) { // tried to parse response string as json, but could not - then just put error string to div
$loginForm.find('.error:first').html(xhr.responseText);
}
},
success: function(response) {
if (response.redirectTo) {
window.location.href = response.redirectTo;
}
}
});
});
});
</script>
Ссылки:
1) jQuery protectDefault
2) jQuery serializeArray
3) jQuery $ .ajax поля и пояснения
4) ExpressJS обнаруживает запрос ajax
5) ExpressJS req.is