如何发送json作为护照validation后的响应在node.js中

我正在尝试这个git的例子 。

当我将其与我的项目集成在一起时效果很好,但是我想实现的是将json作为对客户端/请求的响应发送,而不是successRedirect:'/ profile'&failureRedirect:'/ signup'。

是否有可能发送一个json,还是有一些其他方法得到相同的?

任何帮助将不胜感激,恩

创build新的路由,例如: /jsonSendres.json ,并使successRedirect: '/jsonSend' 。 这应该做到这一点。

您可以在您的快速应用程序中使用护照的身份validationfunction作为路由中间件。

 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}); }); 

默认情况下,如果身份validation失败,Passport将以401 Unauthorized状态响应,并且不会调用任何其他路由处理程序。 如果authentication成功,则将调用下一个处理程序,并将req.user属性设置为已通过身份validation的用户。

在这里我修改了我的代码发送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' }); }); 

使用护照作为中间件。

 router.get('/auth/callback', passport.authenticate('facebook'), function(req, res){ if (req.user) { res.send(req.user); } else { res.send(401); } }); 
 // 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' }); }); 

有一个官方的自定义callback文档:

 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