2014-10-17 125 views
1

如何從另一個域中的用戶登錄。防爆。主站點具有登錄表單,並且ajax發佈到我的nodejs服務器上的路由。護照JS登錄?

// submit form to node server(app) FROM WEBSITE 
$('#submit-project-form').submit(function(e){ 
    e.preventDefault(); 

    var formData = $(this).serialize(); 

    $.ajax({ 
     url: "http://localhost:3100/login", 
     data: formData, 
     type: "POST", 
     crossDomain: true, 
     dataType: "json", 
     success: function(response){ 
      console.log(response.responseText); 
     }, 
     error: function(response) { 
      var success = $($.parseHTML(response.responseText)).filter("body"); 
      console.log(response.responseText); 
     } 
    }); 

}); 

// Passport POST auth methods. Listen to POST route from website 
app.post('/login', passport.authenticate('local-login', { 
    successRedirect : '/', // re-run user.index which should pass as a user and render profile 
    failureRedirect : '/login', // redirect back to the signup page if there is an error 
    failureFlash : true 
})); 

這將觸發路由,並且我正在獲取登錄我的護照策略所需的電子郵件和密碼。

passport.use('local-login', new LocalStrategy({ 
    usernameField : 'email', 
    passwordField : 'password', 
    passReqToCallback : true // allows us to pass back the entire request to the callback 
}, 
function(req, email, password, done) { // callback with email and password from our form 
    console.log(req.body.email); // returns email entered in cross-domain field 
    console.log(email); // returns email entered in cross-domain field 
    // find a user whose email is the same as the forms email 
    // we are checking to see if the user trying to login already exists 
    AppUser.findOne({ 'local.email' : email }, function(err, user) { 
     // if there are any errors, return the error before anything else 
     if (err) 
      return done(err); 

     // if no user is found, return the message 
     if (!user) 
      return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash 

     // if the user is found but the password is wrong 
     if (!user.validPassword(password)) 
      return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata 

     // all is well, return successful user 
     return done(null, user); 

    }); 

})); 

CORS是服務器的NodeJS上啓用,它的作品,因爲我可以將付款提交跨域,我也得到來自服務器的響應。

我認爲這個問題是護照有successRedirect和地方與位於這個問題,我可能需要一個自定義的成功的功能?有任何想法嗎?

回答

1

好像加入xhrFields給Ajax使工作。我會繼續測試,但我可以使用跨域POST進行登錄,非常酷。

xhrFields: { 
    withCredentials: true 
},