2016-02-29 61 views
0

我正在使用節點4.3.1,表達4.13.1和認證工具是本地通行證。我試圖通過ajax發佈登錄表單數據。所以我想在不刷新頁面的情況下顯示錯誤消息。但第一步是殺死我。nodejs不接受表單數據由ajax

觀點:

<form id="login_form" action="#"> 
    <input type="hidden" id="csrf" name="_csrf" value="{{_csrfToken}}"> 
     <input id="email" name="email" type="email" placeholder="Email"> 
     <input id="password" name="password" type="password" placeholder="Password"> 
     <button type="" id="forLogin">Login</button> 
    </form> 
//POST Ajax 
$('#forLogin').on('click', function(e){ 
    e.preventDefault(); 
    var data= {}; 
    data.email = $('#email').val(); 
    data.password = $('#password').val(); 
    data._csrf = $('#csrf').val(); 

    $.ajax({ 
     type: 'POST', 
     url: '/login', 
     data: JSON.stringify(data),  // node.js accepts request but responds 403 

//  data: $('#login_form').serialize(), 
//   don't accept any request 
     dataType: 'json', 
//  headers: {'X_CSRF_TOKEN':'{{_csrfToken}}'}, 
//   not working too 
     success: function(result){ 
       console.log('success'); 
       if(!result){ 
        console.log('No result'); 
       } 
      }, 
      error: function (xhr, ajaxOptions, thrownError) { 
       console.log(xhr.status); 
       console.log(thrownError); 
      } 
     }); 
    }); 

如果我使用data: JSON.stringify(data),火狐檢查顯示十分可疑參數: {"email":"[email protected]","password":"test","_csrf":"wOEsa4s2-I9dmSQuT9djm0kyrrp9WcZWj6U0"}:"" 即使該參數傳遞好,我不知道它會工作。

,並在這些情況下:data: $('#login_form')data:data

我沒有得到任何迴應。但參數看起來似乎是合理的,而且關鍵:attr對看起來很整齊。

router.js

router.post('/login', function(req, res, next){ 
passport.authenticate('local-login', function(err, user, info){ 
console.log(req.body); 

if (err) { return next(err); } 
if (!user) { 
    console.log('authentication fail'); 
    return res.json({ajaxMsg: 'authentication fail'}); 
} 
req.logIn(user, function(err) { 
    if (err) { return next(err); } 
    // Redirect if it succeeds 
    return res.redirect('/'); 
    }); 
    }) 
}); 

passport.js

var passport = require('passport'), 
    LocalStrategy = require('passport-local').Strategy, 
    User = require('../models/User.js'), 
    bcrypt = require('bcrypt'); 

passport.serializeUser(function(user, done){ 
    done(null, user.email); 
}); 
passport.deserializeUser(function(email, done){ 
    User.findOne(email, function(err, user){ 
     done(err, user); 
    }); 
}); 
passport.use('local-login', 
      new LocalStrategy({ 
    usernameField: 'email', 
    passwordField: 'password', 
    passReqToCallback: true 
}, 
    function(req, email, password, done){ 
    User.findOne({'email': email}, function(err, user){ 
     if(err) return done(err); 
     if(!user){ 
      console.log('wrong email'); 
      req.flash('email', req.body.email); 
      return done(null, false, req.flash('error_messages', 'No user found')); 
     } 
     if(!user.authenticate(password)){ 
      console.log('wrong password'); 
      req.flash('email', req.body.email); 
      return done(null, false, req.flash('error_messages', 'Password does not Match')); 
     } 
     console.log('Login Success'); 
     return done(null, user); 
    }); 
}) 
); 
module.exports = passport; 

我意識到,有沒有辦法使用連接閃光燈消息,而無需刷新頁面,所以我試圖取代其他邏輯很難了解done()方法如何工作

回答

0

我解決了這個問題。

router.post('/login', function(req, res, next) { 
    if(req.body.email.length == 0 || req.body.password.length == 0) { 
    return res.json({error: 'enter a id and a pw'}); 
    } 
    passport.authenticate('local-login', function(err, user, info) { 
    if (err) { 
     return res.json({srverror: err}); 
    } 
    // Redirect if it fails 
    if (!user) { 
     return res.json({error: info.msg}); 
    } 
    if (user) { 
     req.logIn(user, function(err) { 
     if (err) { return res.json({srverror: err}); } 
     // Redirect if it succeeds 
     res.send({redirect: '/'}); 
     }); 
    } 
    })(req, res, next); 
}); 

(REQ,RES,下一個)是我所需要的代碼。 但我不能完全理解它爲什麼起作用。

0

而不是

if (err) { return next(err); } 

嘗試

if (err) { return res.json({error: err}); } 

,如果你得到一個錯誤,那麼你就必須理清了這一點,但我相信這是你的問題。您的請求是否在記錄器上返回404或500?

完成是它使用的回調填充req.session對象。

另外我相信你沒有正確使用next()。除非你的/login是某種中間件,並且你期望在它結束後發生其他事情

+0

我得到了403禁止狀態代碼 –

+0

@BaroqueCode你得到迴應改變這種ERR功能之後 – Datsik

+0

沒有,什麼都沒有改變 '數據:JSON.stringify(數據)'使403種狀態, '數據:$('# login_form')。serialize()'做出任何迴應 –