我正在尝试git example。
当我将它与我的项目集成时效果很好,但我想要实现的是发送json作为对客户端/请求的响应,而不是successRedirect:'/ profile'& failureRedirect:'/ signup'。
是否可以发送json,还是有其他方法可以获得相同的效果?
任何帮助将不胜感激,TU
答案 0 :(得分:5)
您可以在快递应用程序中使用护照的身份验证功能作为路由中间件。
app.post('/login',
passport.authenticate('local'),
function(req, res) {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
// Then you can send your json as response.
res.json({message:"Success", username: req.user.username});
});
默认情况下,如果身份验证失败,Passport将以401 Unauthorized状态响应,并且不会调用任何其他路由处理程序。如果身份验证成功,将调用下一个处理程序,并将req.user
属性设置为经过身份验证的用户。
答案 1 :(得分:4)
创建新路线,例如:/jsonSend
,其中包含res.json
并制作successRedirect: '/jsonSend'
。应该这样做。
答案 2 :(得分:3)
这里我修改了我的代码以发送json作为响应
// process the signup form
app.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/successjson', // redirect to the secure profile section
failureRedirect : '/failurejson', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
app.get('/successjson', function(req, res) {
res.sendfile('public/index.htm');
});
app.get('/failurejson', function(req, res) {
res.json({ message: 'hello' });
});
答案 3 :(得分:2)
有一个官方的自定义回调文档:
app.get('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/users/' + user.username);
});
})(req, res, next);
});
https://github.com/passport/www.passportjs.org/blob/master/views/docs/authenticate.md
答案 4 :(得分:1)
使用护照作为中间件。
function rfl($dir) {
$search=$dir."[^~]*";
echo "searching for: $search<br/>";
$search= preg_grep('!^'.preg_quote($dir).'[^~]!', glob($dir.'*')); //find every file and directory not starting with ~. directories are returned with / afterwards
$list=array();
foreach ($search as $file) {
if (is_dir($file)) {
$list=array_merge($list,rfl($file.'/')); //recursively search for valid files in directories
echo 'D: ' . $file.'<br/>';
} else {
$list[]=$file; //add files to list
echo 'F: ' . $file.'<br/>';
}
}
return $list;
}
print_r(rfl('code/'));
答案 5 :(得分:-1)
// process the signup form
app.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/successjson', // redirect to the secure profile section
failureRedirect : '/failurejson', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
app.get('/successjson', function(req, res) {
res.sendfile('public/index.htm');
});
app.get('/failurejson', function(req, res) {
res.json({ message: 'hello' });
});