我有一些代码,我写的基本上是用支持它的后端API处理登录。
我的问题是,在表单POSTS
到服务器的数据(并且被接受)之后,索引页面(这个表单所在的位置)仍然显示登录表单而不是我在文件中有不同的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 © Barchart™</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 © 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>
我认为这是一个会话问题,但我似乎无法解决这个问题。更重要的是,我甚至无法获得callback
函数来返回所需的数据。