Node.js Nodejs登录会话/重定向问题

Node.js Nodejs登录会话/重定向问题,node.js,express,Node.js,Express,我编写了一些代码,基本上用来处理登录,后端API支持它 我的问题是,在表单将数据发布到服务器(并被接受)后,索引页(与此表单所在的位置相同)仍然显示登录表单,而不是文件中不同的if语句 但是,如果我刷新页面,将显示if语句的正确部分。我整天都在做这件事,我需要一双新的眼睛来审视它,看看我做错了什么: define([ 'lodash', 'log4js', 'path', 'when', 'common/lang/Disposable', 'com

我编写了一些代码,基本上用来处理登录,后端API支持它

我的问题是,在表单
将数据发布到服务器(并被接受)后,索引页(与此表单所在的位置相同)仍然显示登录表单,而不是文件中不同的
if
语句

但是,如果我刷新页面,将显示
if
语句的正确部分。我整天都在做这件事,我需要一双新的眼睛来审视它,看看我做错了什么:

define([
    'lodash',
    'log4js',
    'path',
    'when',
    'common/lang/Disposable',
    'common/commands/CommandHandler',
    'common-node/network/http/Verb',
    'common-node/network/server/endpoints/html/PageContainer',
    'common-node/network/server/endpoints/html/PageEndpoint',
    'common-node/network/server/ServerDefinition',
    'common-node/network/server/ServerFactory.instance',
], function(_, log4js, path, when, Disposable, CommandHandler, Verb, PageContainer, PageEndpoint, ServerDefinition, serverFactory) {
    //'use strict';
    var m;

    var session = require('client-sessions');
    session({
      cookieName: 'GBE_OWNED',
      secret: '12112asdfasdf',
      duration: 30 * 60 * 1000,
      activeDuration: 5 * 60 * 1000,
    });

    var logger = log4js.getLogger('server/GbeSeasonalsWebServer');

    var GbeSeasonalsWebServer = Disposable.extend({
        init: function() {

        },

        start: function(configuration) {
            var port = getContainerPort(configuration.container);
            var state = false;

            var indexHandler = new CommandHandler.fromFunction(function(input) {
                console.log(input || { });

                if(input.logout == ''){
                    session.qry = '';
                    session.Name = '';

                    return {
                        name: '',
                        currentState: false,
                        reloadLogout: true
                    };
                }

                if(typeof session.qry === 'undefined' || session.qry === null || session.qry === ''){
                    //the user isn't logged in
                    state = false;
                }
                else{
                    console.log(session.qry);
                    state = true;
                }

                return {
                    name: session.Name,
                    currentState: state
                };
            });

            var loginHandler = new CommandHandler.fromFunction(function(input) {

                var userName   = input.username;
                var userPass   = input.password;
                var rememberMe = input.remember;
                var retro      = false;
                var iResponse;
                var productIDs = 'USC_SEASONAL_CB,USC_SEASONAL_CB'; // this will be changed when jose gets back to me with the specifics

                var https = require('https');

                var callback = function(response){
                    var str = '';
                    response.on('data', function(chunk){
                        str += chunk;
                    });
                    response.on('end', function () {
                        try{
                            var DOMParser = require('xmldom').DOMParser;

                        }catch(err){
                            return {error: "There appeared to be an error. Please try again."};
                        }

                        var doc = new DOMParser().parseFromString(str,'text/xml');
                        var isSuccessful = doc.firstChild.attributes[1].nodeValue;

                        if(isSuccessful == 'True'){
                            retro = true;
                            //I need to set a session here
                            console.log("The account was logged in successfully.");
                            session.qry =  '?username=' + userName + '&password=' + userPass + '&productids=' + productIDs;
                            //console.log(session.username);
                            if(typeof str === 'undefined' || str === null){return {error: "There appeared to be an error. Please try again."};}
                            session.Name = doc.firstChild.attributes[4].nodeValue + ' ' + doc.firstChild.attributes[5].nodeValue;
                            var state = true;

                            iResponse = function (){
                                return {
                                    name: session.Name,
                                    currentState: true,
                                    reload: true,
                                };
                            };

                        }
                        else{
                            iResponse = function (){
                                return {  
                                    error: "There appeared to be a problem while trying to log you in.",
                                    name: "WHATTHEHELL",
                                    state: false
                                };
                            };
                        }
                        return iResponse; 

                    });
                    response.on('error', function (e) {
                        console.log(e);
                    });
                };

                return https.request('https://secure.barchart.com/banker/getuserpermissions.ashx?username=' + userName + '&password=' + userPass + '&productids=' + productIDs, callback).end(); 
            });

            var definition = ServerDefinition
                .withContainer(
                    new PageContainer(port, '/')
                        .addEndpoint(new PageEndpoint(Verb.GET, '', 'index', indexHandler))
                        .addEndpoint(new PageEndpoint(Verb.POST, '', 'index', loginHandler))
                        .addEndpoint(new PageEndpoint(Verb.GET, '/index', 'index', indexHandler))
                        .addEndpoint(new PageEndpoint(Verb.POST, '/index', 'index', loginHandler))
                        .addEndpoint(new PageEndpoint(Verb.GET, '/signup', 'signup'))
                        .addEndpoint(new PageEndpoint(Verb.POST, '/signup', 'signup'))
                        .addEndpoint(new PageEndpoint(Verb.GET, '/more', 'more'))
                );

            definition.withTemplatePath(path.join(configuration.server.path, configuration.container.http.templatePath));

            _.forEach(configuration.container.http.staticPaths, function(filePath, serverPath) {
                definition.withStaticPath(path.join(configuration.server.path, filePath), serverPath);
            });

            return when.try(function() {
                serverFactory.build(definition);
            }).then(function() {
                return true;
            });
        },

        _onDispose: function() {
            logger.warn('GBE Seasonals web server is being disposed');
        },

        toString: function() {
            return '[GbeSeasonalsWebServer]';
        }
    });

    function getContainerPort(containerConfiguration) {
        var port = parseInt(process.env.PORT);

        if (_.isNaN(port)) {
            port = null;
        }

        return port || containerConfiguration.port || 8080;
    }

    return GbeSeasonalsWebServer;
});
和索引页:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>GBE SEASONALS STAGING SITE &copy; Barchart&trade;</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <!-- Custom theme -->
    <link rel="stylesheet" type="text/css" href="static/css/custom.css">
</head>



<body>
<script type="text/javascript">

    var c = '{{name}}';
    var state = '{{currentState}}';

    {{#if reload}}
        window.location = window.location.href; 
    {{/if}}
    {{#if reloadLogout}}
        window.location = window.location.href.split("?")[0];
    {{/if}}

    if(state==''){window.location = window.location.href; }

</script>



<div class="container">
    <div class = "row">
        <div class="col-md-10 col-md-offset-1">
            <a href="index">
                <img style = "vertical-align:middle;display:inline-block" src="http://www.gbemembers.com/images/GBE_Logo_horiz.png" class="img-responsive">
                <p style="color:white;margin-top:50px;margin-right:20px;font-size:20px" class="pull-right">Seasonals</p>
            </a>
        </div>

    </div>

    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <div class="panel panel-default">
                <div class="panel-heading"></div>

                <div class="panel-body">
                    <div class = "row">
                        {{#if error}}
                            <div class="alert alert-danger" role="alert">
                              <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
                              <span class=""><b>Error:</b></span>
                              {{error}}
                            </div>
                        {{/if}}

                        {{#if currentState}}
                            <div class = "col-md-12">
                                <p class = "pull-right">Welcome back {{name}}! <a href = "?logout">Click here to log out.</a></p>
                            </div>
                        {{else}}        
                        <center>
                            <div class = "col-md-12">
                                <form class="form-inline" style = "width:100%;margin:0 auto;" method="post" action = "?"><label>Already a member? Login here: </label>
                                    <div class="form-group">
                                        <label class="sr-only" for="exampleInputEmail3">Email address</label>
                                        <input type="" class="form-control" id="exampleInputEmail3" placeholder="Email" name = "username">
                                    </div>
                                    <div class="form-group">
                                        <label class="sr-only" for="exampleInputPassword3">Password</label>
                                        <input type="password" class="form-control" id="exampleInputPassword3" placeholder="Password" name = "password">
                                    </div>
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" name = "remember"> Remember me
                                        </label>
                                    </div>
                                    <button type="submit" class="btn btn-default">Sign in</button>
                                    <a href="signup"><input type = "button" value = "Register" class="btn btn-default"></a>
                                </form>
                                <p></p>
                            </div>
                        </center>
                        {{/if}}

                    </div>

                    <div class = "row">
                        <div class = "col-md-12">
                            <div class="jumbotron">
                                <h1>Hello, world!</h1>
                                <p>This is an example of a jumbotron....because you're worth it.</p>
                                <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
                            </div>
                        </div>
                    </div>



                    <div class = "row">
                        <div class = "col-md-12">
                            <p>
                                Freegan tacos before they sold out, health goth sriracha chartreuse kinfolk jean shorts man braid artisan literally. Brooklyn vice hashtag, meh tumblr kombucha marfa readymade. Ennui cold-pressed distillery freegan. Kale chips tilde +1, mumblecore franzen migas paleo. Offal 3 wolf moon before they sold out, health goth disrupt fixie bitters flannel meditation pop-up flexitarian irony meh. Deep v put a bird on it pork belly cardigan etsy. Lumbersexual literally crucifix slow-carb cardigan.
                            </p>
                        </div>
                    </div>
                    <div class = "row">
                        <div class = "col-md-12">
                            <p>Asymmetrical readymade brooklyn, blue bottle master cleanse disrupt artisan +1 actually affogato roof party DIY polaroid next level retro. Brooklyn poutine vegan bitters you probably haven't heard of them. Celiac helvetica master cleanse williamsburg, synth shabby chic fixie. Viral typewriter cred, roof party kombucha readymade offal shabby chic meggings. Gochujang chillwave VHS food truck. Ennui ugh twee, mumblecore sriracha DIY gastropub hella 3 wolf moon pabst kale chips typewriter trust fund direct trade. Neutra microdosing selfies listicle.</p>
                        </div>
                    </div>

                    <div class = "row">
                        <div class = "col-md-12">
                            <p>
                                Gochujang farm-to-table offal, distillery tofu migas skateboard 90's. Ethical ramps hoodie, YOLO vice before they sold out four loko literally mustache post-ironic. Fixie ennui literally lumbersexual photo booth umami disrupt messenger bag man braid polaroid. Cold-pressed aesthetic marfa, vinyl truffaut squid 3 wolf moon sriracha keytar knausgaard echo park. Chambray leggings microdosing mustache migas. Keytar portland chambray, quinoa ugh farm-to-table mustache cred mixtape craft beer. Thundercats chia keytar beard, drinking vinegar mustache man bun slow-carb wayfarers polaroid lo-fi chicharrones.
                            </p>
                        </div>
                    </div>
                    <div class = "row">
                        <div class = "col-md-12">
                            <p>
                                Quinoa cred taxidermy, cold-pressed microdosing offal mustache gluten-free small batch tousled twee wayfarers. Wolf williamsburg normcore lo-fi, tilde seitan hammock bushwick DIY organic single-origin coffee quinoa microdosing man braid. Fap small batch PBR&B microdosing, migas pork belly occupy aesthetic pop-up slow-carb 3 wolf moon. Blue bottle XOXO occupy +1, pabst lomo chicharrones ethical heirloom helvetica asymmetrical. Bushwick shabby chic yr kombucha, flannel truffaut raw denim banh mi bitters gluten-free pickled hoodie letterpress sartorial. YOLO whatever tacos meggings venmo, keytar knausgaard mumblecore. Tilde waistcoat offal, locavore cred umami mlkshk vice lomo lo-fi tousled selvage blog tattooed poutine.
                            </p>
                        </div>
                    </div>
                    <div class = "row">
                        <div class = "col-md-12">
                            <a href = "signup"><button type="button" class="btn btn-primary btn-lg btn-block">Click here to sign up!</button></a>
                        </div>
                    </div>
                </div>

                <div class = "panel-footer">GBE Seasonal &copy; 2016 Barchart</div>
            </div>
        </div>
    </div>

</div> <!-- /container -->


<!-- Let's load the javascript dendencies now -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script type="text/javascript" src = "http://getbootstrap.com/assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>

GBE季节性分期地点和副本;柱状图与贸易;
var c='{name}}';
变量状态=“{currentState}}”;
{{{#如果重新加载}
window.location=window.location.href;
{{/if}
{{#如果重新加载注销}
window.location=window.location.href.split(“?”[0];
{{/if}
如果(state=''){window.location=window.location.href;}
{{{#如果出错}}
错误:
{{error}}
{{/if}
{{{#如果当前状态}}
欢迎回来{{name}

{{else} 已经是会员了?在此处登录: 电子邮件地址 密码 记得我吗 登录

{{/if} 你好,世界! 这是一个巨大的例子…因为你值得

Freegan玉米饼在售罄前,健康哥特人sriracha Chartrese kinfolk牛仔短裤男士编织工匠。布鲁克林副标签,meh tumblr康普茶马法成衣。厌倦冷榨酒厂弗里根。羽衣甘蓝片瓷砖+1,mumblecore franzen migas古董。内脏3狼月售罄前,健康哥特扰乱修复苦味法兰绒冥想弹出灵活讽刺meh。深v在它上面放了一只鸟猪肚开衫等等。Lumbersexually Crossifix慢碳水化合物开衫。

布鲁克林的非对称成衣,蓝色瓶大师级清洁破坏工匠+1实际上是对屋顶派对DIY宝丽来下一级复古。Brooklyn poutine纯素苦酒你可能没听说过。Celiac helvetica master cleanse williamsburg,synth简陋别致修护。病毒式打字机信用,屋顶党康普茶现成内脏破旧别致的麦金格。Gochujang chillwave VHS食品车。厌倦了,咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕噜咕。Neutra微量给药自拍列表

Gochujang农场到餐桌内脏,酿酒厂豆腐米加滑板90年代。道德坡道连帽衫,YOLO vice之前,他们出售了四个loko字面上的胡子后讽刺。Fixie ennui字面意思是伐木性照片亭umami disrupt messenger bag男子编织宝丽来。冷压美感马法,乙烯基松露乌贼3狼月亮sriracha keytar knausgaard echo park。查姆布雷紧身裤微剂量胡须米加斯。凯塔波特兰香布雷,奎奴亚藜,从农场到餐桌的胡须cred混搭工艺啤酒。Thundercats chia keytar胡须,喝醋胡子男人面包慢碳水化合物旅行者宝丽来低保真chicharrones。

奎奴亚藜科植物标本,冷压微量给药,不含麸质的小批量蓬乱的粗花呢旅行者。Wolf williamsburg normcore lo-fi,tilde seitan吊床bushwick DIY有机单一产地咖啡藜麦微量剂量男士编织物。Fap小批量PBR&B微剂量,米加斯猪肚占据美学弹出慢碳水化合物3狼月。蓝瓶XOXO占领+1,帕布斯特·洛莫·奇卡隆民族传家宝赫尔维蒂卡不对称。布什维克破旧别致的yr康普茶,法兰绒粗牛仔布无麸质泡制连帽衫活版裁缝。不管是什么,墨西哥玉米卷都是文莫,凯塔·克努斯加德咕哝着。瓷砖马甲下脚料,locavore cred umami mlkshk副总裁lomo lo-fi蓬乱的布边博客纹身poutine。