【问题标题】:How to passing message to client in passportjs如何在passportjs中将消息传递给客户端
【发布时间】:2015-01-15 10:15:15
【问题描述】:

目前,我遇到了从 nodejs 获取消息的问题

在客户端(与nodejs分开),

'use strict';

angular.module('app').controller('RegisterCtrl', function ($scope, alert, $auth) {
    $scope.submit = function () {
        $auth.signup({
            email: $scope.email,
            password: $scope.password
        })
            .then(function (res) {
                alert('success', 'Account Created!', 'Welcome, ' + res.data.user.email + '! Please email activate your account in the next several days.');
            })
            .catch(function (err) {
                alert('warning', 'Unable to create account :(', err.message);
            });
    };
});

虽然,在 Nodejs 护照上我收到错误“电子邮件已被占用”,但它无法将此消息传递给客户端,客户端只收到 401(未经授权)。 我还安装了 connect-flash 并设置了

app.post('/auth/register', passport.authenticate('local-register', {
    failureFlash : true // allow flash messages
}), function (req, res) {
    emailVerification.send(req.user.email, res, req);
    createSendToken(req.user, res);
});

但仍然没有运气。我怎样才能得到这个消息?谢谢

【问题讨论】:

    标签: node.js passport.js


    【解决方案1】:

    Flash 消息设置为req,并且不在 HTTP 响应中返回。如果您要在服务器上呈现 HTML,您可以使用它,但它不适用于 AJAX。

    虽然我不知道您为什么使用身份验证库来处理注册,但您可以使用custom callback 来实现这一点。一个未经测试的例子:

    app.post('/auth/register', function(req, res, next) {
      passport.authenticate('local-register', function(err, user, info) {
        if (err) return next(err);
        if (user) {
          req.logIn(user, function(err) {
            if (err) return next(err);
            emailVerification.send(req.user.email, res, req);
            createSendToken(req.user, res);
          });
        // Register failed, flash message is in info
        } else {
          res.status(400).json(info);
        }
      })(req, res, next);
    });
    

    【讨论】:

    • 是的,这是经过几个小时研究后的唯一方法。
    猜你喜欢
    • 2023-02-09
    • 1970-01-01
    • 2013-02-21
    • 2010-11-05
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多