我有一个张贴到“ /登录”的表格。在事情app.post("/login",...)
的一面,我使用选项loading: true
渲染“ login.ejs”视图,以便在验证密码并将用户重定向到“ / dashboard”后出现加载圆圈动画。但是节点抛出此错误:
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header (.../node_modules/express/lib/response.js:771:10)
at ServerResponse.location (.../node_modules/express/lib/response.js:888:15)
at ServerResponse.redirect (.../node_modules/express/lib/response.js:926:18)
at bcrypt.compare.then (.../controllers/login.js:17:33)
at <anonymous>
我猜想这与两次快速发送头有关。如果不执行此操作,该如何实现此加载功能?
这是路线:
const express = require('express')
const router = express.Router()
const login_controller = require('../controllers/login')
router.get('/', login_controller.render_view)
router.post('/', login_controller.login_user)
module.exports = router;
这是对应的控制器:
const User = require('../models/user')
const bcrypt = require('bcryptjs')
exports.render_view = (req, res) => {
res.render('login', {loading: false})
}
exports.login_user = async (req, res) => {
res.render('login', {loading: true})
const user = {
email: req.body.email,
password: req.body.password
}
const foundUser = await User.findOne({ email: user.email });
if (foundUser) {
bcrypt.compare(user.password, foundUser.password)
.then((result) => {
if (result) res.redirect('/dashboard')
else console.log(false)
})
.catch((err) => {console.log('Exception thrown\n', err)});
} else {
console.log('User not found')
res.redirect('/login')
}
}
我在其他论坛上看到的回答是,这只能通过AJAX实现,但我不了解AJAX,所以也许您可以留下一个示例,说明如何使用AJAX进行此操作。