2014-03-01 75 views
3

我正在研究一個應用程序,它有服務器上的node.js和mongodb,前端的db和Backbone.js。我正在開發用戶登錄,所以我使用了passport.js庫。我的登錄'post'方法有問題:它不會重定向到另一個頁面(它是SPA,所以我的意思是渲染Backbone視圖)。下面的代碼:登錄驗證後快速重定向

//standard express setup... 

app.post('/api/auth', function(req, res, next) { 
    passport.authenticate('local', function(err, user, info) { 
    if (err) { return next(err) } 
    if (!user) { 
     req.session.messages = [info.message]; 
     return res.redirect('/') 
    } 
    req.logIn(user, function(err) { 
     if (err) { 
    return next(err); 
    } else { 
      console.log('yup, working'); //Can see the response in the console 
    return res.redirect('/api'); 
    } 
}); 
    })(req, res, next); 
}); 

app.get('/api', function (request, response) { 
    response.send('Login successful!'); 
}); 

所以我能看到的console.log消息罰款,對路線的GET請求被觸發......但沒有實際發生。所以我想我已經誤解了'res.redirect'是如何工作的 - 我想在登錄成功後導航到那條路線。我想過使用window.location,但這是一個很好的長期解決方案嗎?我沒有在服務器上使用任何html模板,所以我不能(我不認爲)做'res.render('index')'這樣簡單的事情'

什麼是最好的方式來接近這個?提前致謝。

+0

你可以用簡單的方法解決這個問題,只需使用'window.href'或不使用'res.redirect',而是發送一些客戶端期望的json,以便繼續前進無論應該做什麼。 如果可能的話,保留單個骨幹模型用戶並監視該模型的狀態,然後讓所有其他模型監聽用戶模型並採取行動。 – Gntem

回答

4

在問了這個問題幾天之後,我意識到我沒有正確掌握核心概念,所以我有一個臉掌時刻。讓我回答我自己的問題:

我不需要嘗試從服務器提供頁面,我只需要向客戶端發送響應,並讓Backbone根據收到的響應進行渲染。所以,我的服務器做更多的東西是這樣的:

controller.post('/user', function(req, res, next) { 
    passport.authenticate('local', function(err, user, info) { 
    if (err) { return next(err) } 
     user.save(function(err) { 
    if(err){ 
     console.log(err); 
     return res.json(401); 
    } else { 
     return res.json(200); //SEND RESPONSE - do not try to redirect 
    } 
    }); 

那我的頁面加載和骨幹視圖,就像這樣:

login: function (e) { 
    e.preventDefault(); 
    console.log('submitting login request'); 
    var formValues = { 
    username: $('#inputEmail').val(), 
    password: $('#inputPassword').val() 
    }; 

    var user = new User(); //user model 
    user.set(formValues); 

    function saveUserfunction(){ 
    if(user) { 
     user.save(this.formValues, { 
      success: function(model, response, options) { 
       if (response == 200) { 
        console.log('success :' + response); 
        window.location.href = 'http://localhost:4711/#/api/menu_auth'; //Here's my redirect - the router is listening for this route and will render accordingly 
       } else { 
        console.log('error: '+response); 
       } 

      }, error: //Error handling etc. 

如鳳凰在評論中指出的那樣,最好的辦法這將是聆聽用戶模型。