PassportJS始终显示"用户已经注册"

时间:2017-03-07 01:24:44

标签: ajax node.js express passport.js stripe-payments

我使用护照JS在我的网站上注册用户。在注册请求中,我试图使用Stripe向用户收取费用。我也使用Ajax,因为这是一个单页面应用程序。

似乎很好地完成了代码,但我担心Ajax可能会导致问题。奇怪的是,回应并不总是一样的。有时条纹费用会通过,有时却不会。

问题在于:当我注册为具有用户名的新用户时,我100%肯定不会 - 它会说" UserExistsError:具有给定用户名的用户已经注册"

我如何更改代码以解决此问题?

app.post("/quiz", function(req, res){

    var token = req.body.stripeToken; // Using Express
console.log(' CHARGE STEP 1')
// Charge the user's card:
var charge = stripe.charges.create({
  amount: 2800,
  currency: "usd",
  description: "Example charge",
  source: token,
}, function(err, charge) {
  // asynchronously called
});

    User.findOne({username: req.body.username}, function(err, user){
        console.log(' CHARGE STEP 2')
      if(err) { } 
      if(user) { 
          //this is how you sent the "USER NAME TAKEN ERROR"
          res.json({"message": "false" });
      }
    });
   }); 


      //continue with your registration logic once it has been checked that the username is not taken!!!
      var newUser = new User({username: req.body.username, datapoint: req.body.datapoint});
      User.register(newUser, req.body.password, function(err, user){

            if(err){
            console.log("this error" + err)


          } else {
          passport.authenticate("local")(req, res, function(){
            //  req.flash("success", "Welcome to JobQuiz " + user.username);
            //  res.redirect("jobquiz");
             res.json({"message": "true" });
            //  res.redirect('/jobquiz')
             console.log(' CHARGE STEP 3')

          });

          }

      });
});

AJAX CODE HERE

$(function() {
                $("#checkpaymentForm").on("submit", function(e) {
                    e.preventDefault();
                    $.ajax({
                    url: $(this).attr("action"),
                    type: 'POST',
                    data: $(this).serialize(),
                    dataType:'json',

                 success: function (data) {
                     console.log(data)
                    if (data.message === "false") {
                        $('#testERROR').html('Whoops, that username is taken')
                    }
                      else if (data.message === "true") {
                        $('#testERROR').html('Thank you for joining!')

                      }

                 }

                    });
                });

                });

0 个答案:

没有答案