node.js - 如何在passportjs中向客户端传递消息

标签 node.js passport.js

目前,我从nodejs获取消息时遇到问题 enter image description here

在客户端(与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 Passport 上我收到错误“电子邮件已被占用”,但它无法将此消息传递给客户端,客户端只收到 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);
});

但还是没有运气。我怎样才能收到这条消息?谢谢

最佳答案

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

关于node.js - 如何在passportjs中向客户端传递消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27961137/

相关文章:

node.js - COR 错误 : Google Oauth from React to Express (PassportJs validation)

node.js - 在 while 循环中运行 ffmpeg 会导致内存泄漏

javascript - 在 Javascript 中,如何重新排列数组

javascript - Javascript 中的元组列表

node.js - Docker - 在 docker 容器日志中找不到模块

node.js - 如何在没有访问 token 的情况下获取 Google 联系人?

node.js - 如何在没有 Lambda 插件的情况下使用 Node.js 在自己的服务器上使用 alexa-sdk 运行 Alexa 技能?

mysql - PhpMyAdmin 不会生成正确的 JSON 导出文件吗?在 Unix 上用什么替换 ^M 字符?

node.js - 如何知道用户是否使用passport.js 登录?

node.js - Passport.js 阳性结果