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

pit*_*itu 7 node.js express passport-facebook passport-local

我正在尝试这个git示例.

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

是否可以发送json,还是有其他方法来获得相同的?

任何帮助将不胜感激,TU

pit*_*itu 6

在这里我修改了我的代码以发送 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' });
});
Run Code Online (Sandbox Code Playgroud)


Mid*_*vin 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});
  });
Run Code Online (Sandbox Code Playgroud)

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