简体   繁体   English

Node.js / Express / Jade + Passport.js失败重定向错误地呈现页面

[英]Node.js/Express/Jade + Passport.js failureRedirect incorrectly rendering page

On a failed authentication at /login, passport.js saves an error message using failureFlash and redirects to /login (the same page). 如果/ login上的身份验证失败,passport.js会使用failFlash保存一条错误消息,然后重定向到/ login(同一页)。 The sent HTML is correct (ie, includes the failureFlash message), but is rendered incorrectly on the client side as 'undefined,' despite (in the Jade template) being in logic that guarantees it's defined. 发送的HTML是正确的(即,包括failureFlash消息),但是尽管在Jade模板中具有保证已定义的逻辑,但在客户端却被错误地显示为“未定义”。 My route for the HTML (GET /login) and for the submission (POST /login) use the same URL; HTML(GET / login)和提交(POST / login)的路由使用相同的URL; could that be part of the problem? 那可能是问题的一部分吗? The whole code-base can be found here . 整个代码库可以在这里找到。


app.js local strategy app.js本地策略

passport.use(new LocalStrategy(
    function(username, password, done) {
        // asynchronous verification, for effect...
        process.nextTick(function () {
            var user = {'id': 1};
            if(username !== "asdf") {
                return done(null, false, { error: 'Unknown user '+username+'.'});
            }else if(password !== "zxcv") {
                return done(null, false, { error: 'Invalid password.'})
            }

            return done(null, user);
    });
  }
));

app.js login GET route app.js登录GET路线

app.get('/login', function(req, res) {
    var m1 = req.flash('error')[0]
    console.log(m1)
    res.render('login', { user: req.user, message: String(m1), sample: "Sanity check."});
});

app.js login POST route app.js登录POST路由

app.post('/login', 
    passport.authenticate('local', { failureRedirect: '/login', failureFlash: 'THIS IS A SANITY CHECK ERROR', successFlash: 'Welcome!' }),
    function(req, res) {
        console.log('User login successful.');
        var redirect_to = req.session.redirect_to || '/'
        delete req.session.redirect_to;
        res.send({redirect: String(redirect_to)})
        //res.redirect(200, redirect_to);

    });
    app.get('/logout', function(req, res){
        req.logout();
        res.redirect(200, '/');
    });

client_login.js served with /login's HTML client_login.js与/ login的HTML一起提供

$(document).on('pageinit', function() {
    $(document).on('click', '#submit', function() {
        if($('#username').val().length > 0 && $('#password').val().length > 0){
            // Send data to server through the ajax call
            // action is functionality we want to call and outputJSON is our data
            $.ajax({
                url: '/login',
                data: {action : 'login', username : $('#username').val(), password : $('#password').val()},
                type: 'post',
                async: 'true',
                dataType: 'json'
            })
            .done(function (result) {
                console.log('Done!');
                window.location.replace(result.redirect);
            })
            .always(function (result) {
                console.log('Always!');
            })
            .fail(function (request,error) {
                console.log('Fail!');
                // This callback function will trigger on unsuccessful action
                //alert('Network error has occurred please try again!');
            })
        } else {
            if($('#username').val().length <= 0 && $('#password').val().length > 0) {
                alert('Please fill in your username.');
            } else if($('#username').val().length > 0 && $('#password').val().length <= 0) {
                alert('Please fill in your password.');
            } else {
                alert('Please fill in your username and password.');    
            }
        }
        return false; // cancel original event to prevent form submitting
    })
})

login.jade login.jade

extends layout

block content
    h1= title


    if locals.expose.exists['client_login.js']
        script(src='/dist/javascripts/client_login.js')
    else
        script(src='/javascripts/client_login.js')


    div(style='max-width: 300px; margin:0 auto')
        p(style='text-align: left') Please login to continue.
        - if(typeof message !== 'undefined' && message.length > 0)
            p Error! #{message}
        p= sample

        form(role='form', action='/login', method='post')
            .form-group
                input.form-control(type='text', data-clear-btn="true", name="username", id="username", value="", placeholder='Username')
            .form-group
                input.form-control(type='password', data-clear-btn="true", name="password", id="password", value="", placeholder='Password')
            .form-group
                button(type='submit', name='submit', id='submit' class="ui-btn ui-corner-all") Submit

HTML as sent from the server at bottom, rendered page at top. 从服务器发送的HTML在底部,渲染页面在顶部。 Note "undefined" vs "THIS IS A SANITY CHECK ERROR". 注意“未定义”与“这是一个完整性检查错误”。 Also note this project uses jQuery Mobile. 另请注意,该项目使用jQuery Mobile。 Any ideas on what might be causing this behavior? 关于什么可能导致此行为的任何想法? The page's javascript shouldn't touch it, but there's also no visible flickering on redirect, which is good, but makes me suspicious. 该页面的javascript不应使用它,但是在重定向上也没有可见的闪烁,这很好,但是让我感到怀疑。

从服务器发送的HTML在底部,渲染页面在顶部。注意“未定义”与“这是一个完整性检查错误”。

Well, I'm dense. 好吧,我很稠密。 You can't redirect in response to an AJAX post. 您无法重定向以回复AJAX帖子。

So, I modified the AJAX post as below: 因此,我修改了AJAX帖子,如下所示:

        .fail(function (request,error) {
            console.log('Fail!');
            window.location.replace(window.location.href);

        })

The window.location.replace(window.location.href); window.location.replace(window.location.href); feels a little clumsy & there is probably a better way to approach a page refresh, but for the moment, this works. 感觉有点笨拙,可能有更好的方法来刷新页面,但是目前,这是可行的。

... This is why I post here. ...这就是为什么我在这里发布。 Rubber ducky debugging works. 橡皮鸭调试工程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM