gpt4 book ai didi

mysql - 为什么选择"is"再次播放后无法更新我的 html 模型?

转载 作者:行者123 更新时间:2023-11-29 16:04:26 26 4
gpt4 key购买 nike

我正在尝试更新我的数据库以显示新分数,但它总是返回为空。我知道该元素已创建,当我检查时它一直说它为空。我已使用控制台日志看到我正在调用该函数,但无法进一步调试?

createDB.sql

DROP DATABASE IF EXISTS THUNTDB;

CREATE DATABASE THUNTDB;

use THUNTDB;

CREATE TABLE USER (
USER_ID int NOT NULL AUTO_INCREMENT,
USER_EMAIL varchar(255) UNIQUE NOT NULL,
USER_PASS varchar(60) NOT NULL,
USER_LOW int NOT NULL,
PRIMARY KEY (USER_ID)
);

index.html

<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<style>
#loginBtn, #logoutBtn, #registerBtn, #resetLowBtn
{
display: none;
}

a, a:hover
{
color: white;
}
.box
{
height: 50px;
background-color: black;
border: white 2px solid;
}

.prize
{
background-color: green !important;
}

.flipped
{
background-color: red !important;
}

.selected
{
color: blue;
}
</style>
</head>

<body>
<div>
<div class="jumbotron jumbotron-fluid mb-0">
<div class="container">
<h1 class="display-4">THUNT</h1>
<p class="lead">The coolest thunt on the web!</p>
</div>
</div>
<div class="">
<ul class="nav justify-content-start border p-2 bg-dark text-light">
<li class="nav-item">
<a href="#" id='resetLowBtn' class='nav-link'>Reset Low Score</a>
</li>
<li class="nav-item">
<a href="#" id='loginBtn' class='nav-link'>Login</a>
</li>
<li class="nav-item">
<a href="#" id='registerBtn' class='nav-link'>Register</a>
</li>
<li class="nav-item">
<a href="#" id='logoutBtn' class='nav-link'>Logout</a>
</li>
<li class="nav-item">
<span id="msg"></span>
</li>
</ul>
<div class="container">
<!--boxes-->
<div id='game'>
<div id='boxes' class='row'>
</div>

<p>Guesses: <span id='guesses'>0</span> Low Score: <span id='lowScore'>N/A</span></p>
</div>
</div>

</div>

<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<!--put your modal dialogs here...-->
<div id='confirm' class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header bg-dark text-light">
<h5 class="modal-title">Play Again?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<p>Would you like to play again?</p>
</div>
<div class="modal-footer">
<button id='yes' type="button" class="btn btn-primary">Yes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
<div id='loginDlg' class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header bg-dark text-light">
<h5 class="modal-title">Login</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<h4>Login</h4>
<form class="border border-primary p-3">
<div class="form-group">
<input type="text" class="form-control" id="email" name="email" placeholder="Email">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
</form>
</div>
<div class="modal-footer">
<button id='confirmLoginBtn' type="button" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>

<div id='registerDlg' class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header bg-dark text-light">
<h5 class="modal-title">Register</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<h4>Register</h4>
<form class="border border-primary p-3">
<div class="form-group">
<input type="text" class="form-control" id="regEmail" name="regEmail" placeholder="Email">
</div>
<div class="form-group">
<input type="password" class="form-control" id="regPassword" name="regPassword" placeholder="Password">
</div>
</form>
</div>
<div class="modal-footer">
<button id='confirmRegisterBtn' type="button" class="btn btn-primary">Register</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>

$(document).ready(function() 
{
// model ....
let model = {};
let Gmodel= {};

function initializeModel()
{
sendRequest("whoIsLoggedIn", function(){});
let boxCount = 10;
Gmodel.guesses = 0;
Gmodel.boxes = [];
let prize = Math.floor(Math.random() * boxCount);
for (var i = 0; i < boxCount; i++)
{
Gmodel.boxes.push({flipped: false, prize: false});
}
Gmodel.boxes[prize].prize = true;
Gmodel.gameOver = false;
}

// view...
function updateView()
{
console.log(model);
console.log(Gmodel);
if (model.result == undefined)
{
$("#msg").text(model.error);
$("#logoutBtn").hide();
$("#loginBtn").show();
$("#registerBtn").show();
$("#resetLowBtn").hide();
$("#game").hide();
}
else
{
$("#logoutBtn").show();
$("#resetLowBtn").show();
$("#loginBtn").hide();
$("#registerBtn").hide();
$("#msg").text("Hello " + model.result.email);
$("#game").show();
$("#boxes").empty();
for (var i in Gmodel.boxes)
{
let item = $("<div class='col-6 box'></div>");
if (Gmodel.boxes[i].flipped && Gmodel.boxes[i].prize)
{
item.addClass("prize");
}
else if (Gmodel.boxes[i].flipped && !Gmodel.boxes[i].prize)
{
item.addClass("flipped");
}
item.attr("id", i);
$("#boxes").append(item);
}

$("#guesses").text(Gmodel.guesses);
$("#lowScore").text(model.result.low);
}
}

// controller ...
function sendRequest(url, callback)
{
var jqxhr = $.get(url);
jqxhr.done(function(json)
{
model = json;
updateView();
if (callback !== undefined)
callback();
})
jqxhr.fail(function(json)
{
let error = JSON.stringify(json);
model.error = error;
updateView();
})
}

$(document).on("click",".box",function()
{
if (Gmodel.gameOver == true)
{
return;
}

let i = $(this).attr("id");
if (!Gmodel.boxes[i].flipped)
{
Gmodel.guesses = Gmodel.guesses+1;
Gmodel.boxes[i].flipped = true;
if(Gmodel.boxes[i].prize)
{
Gmodel.gameOver = true;
$('#confirm').modal('show');
}
else
{
updateView();
}
}
});

$('#yes').click(function()
{
$('#confirm').modal('hide');
sendRequest("updateLow?low=" + Gmodel.guesses, function(){});
sendRequest("whoIsLoggedIn", function(){});
initializeModel();
updateView();


});

$('#loginBtn').click(function()
{
$('#password').val('');
$('#loginDlg').modal('show');
});

$('#registerBtn').click(function()
{
$('#regEmail').val('');
$('#regPassword').val('');
$('#registerDlg').modal('show');
});

$('#logoutBtn').click(function()
{
sendRequest("logout", function()
{
$("#boxes").empty();
initializeModel();
updateView();
});

});

$('#confirmLoginBtn').click(function()
{
let email = $('#email').val().trim();
let password = $('#password').val().trim();

sendRequest("login?email="+email+"&password="+password, function ()
{
// if (model.error == undefined)
// sendRequest("listSongs");
});
$('#loginDlg').modal('hide');
});

$('#confirmRegisterBtn').click(function()
{
let email = $('#regEmail').val().trim();
let password = $('#regPassword').val().trim();
sendRequest("register?email="+email+"&password="+password, function ()
{
// if (model.error == undefined)
// sendRequest("listSongs");
});

$('#registerDlg').modal('hide');
});

// run...
initializeModel();
updateView();
});


</script>
</body>

服务器.js

const express = require('express');
const app = express();

// added so we can serve index.html...
var http = require('http');
var fs = require('fs');

var mysql = require('mysql');

// install first using npm install bcrypt
const bcrypt = require('bcrypt');

const conInfo =
{
host: process.env.IP,
user: process.env.C9_USER,
password: "",
database: "THUNTDB"
};

var session = require('express-session');
app.use(session({ secret: 'happy jungle',
resave: false,
saveUninitialized: false,
cookie: { maxAge: 600000 }}))

app.all('/', serveIndex);
app.all('/whoIsLoggedIn', whoIsLoggedIn);
app.all('/register', register);
app.all('/login', login);
app.all('/logout', logout);
app.all('/updateLow', updateLow);



app.listen(process.env.PORT, process.env.IP, startHandler())

function startHandler()
{
console.log('Server listening on port ' + process.env.PORT)
}


function updateLow(req, res)
{
var con = mysql.createConnection(conInfo);

console.log("@updateLow");
let sql = `UPDATE USER
SET USER_LOW = ?
WHERE USER_ID = ?`;

let data = [req.query.low, req.session.user.result.id];

// execute the UPDATE statement
if(req.query.low < req.session.user.result.low || isNaN(req.session.user.result.low)){
con.query(sql, data, (error, results, fields) => {
if (error){
return console.error(error.message);
}
console.log('Rows affected:', results.affectedRows);
});
}
}

function whoIsLoggedIn(req, res)
{
if (req.session.user == undefined)
writeResult(req, res, {'error' : 'Nobody is logged in.'});
else
writeResult(req, res, req.session.user);
}

function register(req, res)
{
if (req.query.email == undefined || !validateEmail(req.query.email))
{
writeResult(req, res, {'error' : "Please specify a valid email"});
return;
}

if (req.query.password == undefined || !validatePassword(req.query.password))
{
writeResult(req, res, {'error' : "Password must have a minimum of eight characters, at least one letter and one number"});
return;
}

var con = mysql.createConnection(conInfo);
con.connect(function(err)
{
if (err)
writeResult(req, res, {'error' : err});
else
{
// bcrypt uses random salt is effective for fighting
// rainbow tables, and the cost factor slows down the
// algorithm which neutralizes brute force attacks ...
let hash = bcrypt.hashSync(req.query.password, 12);
con.query("INSERT INTO USER (USER_EMAIL, USER_PASS, USER_LOW) VALUES (?, ?,?)", [req.query.email, hash,10], function (err, result, fields)
{
if (err)
{
if (err.code == "ER_DUP_ENTRY")
err = "User account already exists.";
writeResult(req, res, {'error' : err});
}
else
{
con.query("SELECT * FROM USER WHERE USER_EMAIL = ?", [req.query.email], function (err, result, fields)
{
if (err)
writeResult(req, res, {'error' : err});
else
{
req.session.user = {'result' : {'id': result[0].USER_ID, 'email': result[0].USER_EMAIL, 'low': result[0].USER_LOW}};
writeResult(req, res, req.session.user);
}
});
}
});
}
});

}

function login(req, res)
{
if (req.query.email == undefined)
{
writeResult(req, res, {'error' : "Email is required"});
return;
}

if (req.query.password == undefined)
{
writeResult(req, res, {'error' : "Password is required"});
return;
}

var con = mysql.createConnection(conInfo);
con.connect(function(err)
{
if (err)
writeResult(req, res, {'error' : err});
else
{
con.query("SELECT * FROM USER WHERE USER_EMAIL = ?", [req.query.email], function (err, result, fields)
{
if (err)
writeResult(req, res, {'error' : err});
else
{
if(result.length == 1 && bcrypt.compareSync(req.query.password, result[0].USER_PASS))
{
req.session.user = {'result' : {'id': result[0].USER_ID, 'email': result[0].USER_EMAIL, 'low': result[0].USER_LOW}};
writeResult(req, res, req.session.user);
}
else
{
writeResult(req, res, {'error': "Invalid email/password"});
}
}
});
}
});
}

function logout(req, res)
{
req.session.user = undefined;
writeResult(req, res, {'error' : 'Nobody is logged in.'});
}

function writeResult(req, res, obj)
{
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(obj));
res.end('');
}

function validateEmail(email)
{
if (email == undefined)
{
return false;
}
else
{
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
}

function validatePassword(pass)
{
if (pass == undefined)
{
return false;
}
else
{
var re = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
return re.test(pass);
}
}

function serveIndex(req, res)
{
res.writeHead(200, {'Content-Type': 'text/html'});
var index = fs.readFileSync('index.html');
res.end(index);
}

***我复制的代码中缺少一个 script 标记,位于 jquery 上方、div 之后。它给文本框带来了问题,或者更确切地说我是。

我想弄清楚为什么我在选择再次玩后似乎无法更新低分。如果我注销,它将在我重新登录时更新,但在选择再次玩后不会更新。

最佳答案

我明白了。我需要添加另一个 SQL 语句来重新连接到更新后的用户。

function updateLow(req, res)
{
var con = mysql.createConnection(conInfo);

console.log("@updateLow");
let sql = `UPDATE USER
SET USER_LOW = ?
WHERE USER_ID = ?`;

let data = [req.query.low, req.session.user.result.id];



if(req.query.low < req.session.user.result.low || isNaN(req.session.user.result.low)){
con.query(sql, data, (error, results, fields) => {
if (error){
return console.error(error.message);
}
else
{
con.query("SELECT * FROM USER WHERE USER_EMAIL = ?", [req.session.user.result.email], function (err, result, fields)
{
if (err)
writeResult(req, res, {'error' : err});
else
{
req.session.user = {'result' : {'id': result[0].USER_ID, 'email': result[0].USER_EMAIL, 'low': result[0].USER_LOW}};
writeResult(req, res, req.session.user);
}
});
}
console.log('Rows affected:', results.affectedRows);
});
}
}

关于mysql - 为什么选择"is"再次播放后无法更新我的 html 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55874046/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com