Kay*_*ast 4 javascript ajax jquery node.js passport.js
如果我使用表单字段发送登录请求action="/login", method="post",它可以正常工作.与此处或此处提供的代码类似.
但如果相反,如果我使用相同的信息发送jquery/ajax,那么护照似乎不起作用.没有通过护照进行实际登录,但是ajax调用给出了误导性的成功消息.
以下不起作用.虽然我收到"登录成功"消息,但登录并没有真正发生.
$('#login_button').click(function () {
var email = $('#email').val();
var password = $('#password').val();
alert ('email/pass:' + email + ", " + password);
$.ajax({
type: "POST",
url: "/login",
data: { email: email , password: password },
dataType: 'html'
})
.done(function () {
console.log("http request succeeded");
alert("login success");
});
});
Run Code Online (Sandbox Code Playgroud)
我需要使用该ajax方法,以便在成功登录后我可以在客户端做一些有用的事情.例如,开始socket.io.
请帮忙.我在这里修改了代码:my-modified-code
我尝试了你的代码和Passport-wise它的工作原理.我做了"本地注册","注销",然后"本地登录",并成功通过身份验证,但在UI中没有任何表示.
这与您正在讨论的302相关 - 服务器回复302因为您已定义successRedirect : '/profile',然后jQuery跟随重定向并收到它无法解析的HTML,因为它需要JSON.由于您没有.fail()在$.ajax通话中定义回调,因此您看不到它.
会议很好,虽然可以手动查看/profile.
当您使用常规HTML表单登录时,浏览器将发送单个HTTP请求并根据响应进行操作(例如,呈现HTML页面,或者如果它是302则执行重定向).同样的情况发生了但是在你调用时在不同的上下文中$.ajax- AJAX调用遵循重定向,因为它发出了请求,但浏览器没有.
您应该为AJAX和HTML登录使用单独的路由,或使用自定义回调并确定要返回的内容req.accepts().
单独的路线可以是例如.
// AJAX logins to this URL, redirect on client side using
// window.location.href if login succeeds
app.post('/login/ajax', passport.authenticate('local-login'));
// HTTP login form send to this URL
app.post('/login', passport.authenticate('local-login', {
successRedirect : '/profile',
failureRedirect : '/login',
failureFlash : true
}));
Run Code Online (Sandbox Code Playgroud)
自定义回调可能是这样的(未经测试):
app.post('/login', function(req, res, next) {
passport.authenticate('local-login', function(err, user, info) {
switch (req.accepts('html', 'json')) {
case 'html':
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/profile');
});
break;
case 'json':
if (err) { return next(err); }
if (!user) { return res.status(401).send({"ok": false}); }
req.logIn(user, function(err) {
if (err) { return res.status(401).send({"ok": false}); }
return res.send({"ok": true});
});
break;
default:
res.status(406).send();
}
})(req, res, next);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4233 次 |
| 最近记录: |