0

私はnodejsとそのルートシステムが初めてです。「送信後にヘッダーを設定できません」というメッセージが表示されます。本番モードのみ Heroku のみ (ローカルでは正常に動作します)。

// ログイン =========================================

router.get('/', ifLoggedOut, function(req, res, next){
    res.render('login', { message: req.flash('message')});
});

router.post('/login', function(req, res, next){
    var username = req.body.username;
    var password = req.body.password;

    req.checkBody('username', 'Username field is required').notEmpty();
    req.checkBody('username', 'Password field is required').notEmpty();

    req.checkBody('password', 'Invalid Credintials').len(8, 20);
    req.checkBody('username', 'Invalid Credintials').len(4, 20);

    var errors = req.validationErrors();

    if(errors) {
    res.render('login.ejs', {errors: errors});
    } else {
        passport.authenticate('local-login', {
            successRedirect : '/list', // redirect to the secure list section
            failureRedirect : '/', // redirect back to the signup page if there is an error
            failureFlash : true // allow flash messages
        })(req, res, next);
    }
});

// 関数 ============================================== =

function ifLoggedIn(req, res, next) {

// if user is authenticated in the session, carry on 
    if (req.isAuthenticated()) {
        return next();
    }
  console.log("cannot found in session");
  res.redirect('/');

}

function ifLoggedOut(req, res, next){
    if(req.isAuthenticated()){
        res.redirect('/list');
    }
    return next();
}


app.use('/', router);
}

// Heroku のエラーログ

2015-08-20T07:37:07.490091+00:00 app[web.1]: エラー: 送信後にヘッダーを設定できません。2015-08-20T07:37:07.490096+00:00 アプリ [web.1]: ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11) で 2015-08-20T07:37:07.490098+00:00 アプリ[ web.1]: ServerResponse.header (/app/node_modules/express/lib/response.js:718:10) で 2015-08-20T07:37:07.490099+00:00 app[web.1]: ServerResponse で。送信 (/app/node_modules/express/lib/response.js:163:12) 2015-08-20T07:37:07.490101+00:00 app[web.1]: 完了時 (/app/node_modules/express/lib /response.js:957:10) 2015-08-20T07:37:07.490103+00:00 app[web.1]: View.exports.renderFile [エンジンとして] (/app/node_modules/ejs/lib/ejs .js:355:10) 2015-08-20T07:37:07.490105+00:00 app[web.1]: View.render で (/app/node_modules/express/lib/view.js:126:8) 2015 -08-20T07:37:07.490106+00:

4

1 に答える 1

2

この問題は、コールバックが呼び出された後に2 つのレンダリング呼び出しが行われる関数ifLoggedInifLoggedOut関数にありました。コールバックを使用することで、これらの間違いを回避できます。next()redirect()returnnext()

元のコード:

function ifLoggedOut(req, res, next){
    if(req.isAuthenticated()){
        res.redirect('/list');
    }
    return next();
}

修正版:

    function ifLoggedOut(req, res, next){
        if(req.isAuthenticated()){
            return res.redirect('/list');
        } 
        return next();
    }

またはif else、適切に使用できた可能性があります(を必要とせずにreturn):

if(req.isAuthenticated()){
    res.redirect('/list');
} else {
    next();
}

それでも、returnこのような間違いを避けるには、 を使用することをお勧めします。

于 2015-08-20T08:17:12.947 に答える