【发布时间】:2017-10-13 17:53:47
【问题描述】:
我正在尝试在 ajax put 请求之后进行重定向。我打算使用纯 JS 客户端进行验证。
客户:
$(document).ready(function() {
login = () => {
var username = $("[name='username']").val()
var password = $("[name='password']").val()
$.ajax({
type: "put",
url: '/login',
data: {
username: username,
password: password
}
// success: function(response) {
// console.log('Success:')
// console.log(response.user)
// Cookies.set('username', response.user.username)
// Cookies.set('first_name', response.user.first_name)
// Cookies.set('last_name', response.user.last_name)
// Cookies.set('email', response.user.email)
// window.location.href = window.location.origin + '/'
// },
// error: function(error) {
// console.log("Error:")
// console.log(error)
// }
})
}
logout = () => {
console.log("Log out clicked.")
Cookies.remove('username')
Cookies.remove('first_name')
Cookies.remove('last_name')
Cookies.remove('email')
window.location.href = window.location.origin + '/logout'
}
})
服务器:
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('main')
});
router.put('/login', function(req, res) {
// Password is not encrypted here
console.log('req.body')
console.log(req.body)
User.findOne({ username: req.body.username }, function(err, user) {
// Password is encrypted here
if (err) throw err
console.log('user')
console.log(user)
bcrypt.compare(req.body.password, user.password, function(err, result) {
if (result) {
var token = jwt.encode(user, JWT_SECRET)
// return res.status(200).send({ user: user, token: token })
return res.redirect('/')
} else {
return res.status(401).send({error: "Something is wrong."})
}
})
})
})
成功登录后我无法让main.hbs 呈现。我的注释代码有效,但我正在尝试做我的重定向服务器端而不是客户端,因为我被告知它对安全性更好。
【问题讨论】:
-
您的注释代码是正确的工作方式。这里没有安全性损失。无论哪种方式,您的重定向都会传达给用户。服务器端重定向对于 ajax 请求是死路一条,因为该指令不是针对浏览器的,而是针对一些 javascript 处理程序的。
-
谢谢!这真是太好了。我的注释代码对我来说很有意义,我想朝那个方向发展,但我担心用户的安全性。如果我能够在客户端使用 JavaScript(在向服务器提交请求之前),我将能够进行自定义验证,而不是仅限于 HTML5 表单验证。
标签: javascript jquery ajax express