George Pashev

Website of George Pashev (Jidai Mirai)

Scientist, Programmer, Data Scientist, Enterpreneur

Избираема дисциплина "Програмиране с Node.JS"

Избираема дисциплина "Програмиране с Node.JS"

PDF ръководство за упражненията:

Свали

 

Portable версия на програмна среда:

Свали

1. Упражнение: Сървър Express Калкулатор

var express=require('express');
var app=express();
app.get('/', function(req, res){
res.send('Hello World!');


});

app.get('/delete/', function(req, res){
//console.log(result);
res.setHeader('Access-Control-Allow-Origin', '*');

try{
var sqlite3=require("sqlite3").verbose();
var db=new sqlite3.Database("EMSG.db");
db.serialize(function(){
console.log("17");
db.run("DELETE FROM LOG;", function(){
console.log("19");
db.close();
res.send(JSON.stringify({status: "OK"}));

});

});
//db.close();
}catch(error){
console.log({error : error});

}





});

var logResult=function(result, request){
//console.log(result);

try{
var sqlite3=require("sqlite3").verbose();
var db=new sqlite3.Database("EMSG.db");
db.serialize(function(){
db.run("CREATE TABLE "+
" if not exists "+
" LOG("+
"ID INTEGER PRIMARY KEY AUTOINCREMENT, "+
" txt text not null, "+
" request text not null,"+
" time datetime default current_timestamp"+
" );"
);
var stmt=db.prepare("INSERT INTO LOG(txt, request) VALUES(?, ?)");
stmt.run(JSON.stringify(result), JSON.stringify(request));
stmt.finalize();
});
db.close();
}catch(error){
console.log({error : error});

}



}

app.get('/one/', function(req, res){
var result={};
try{
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');

var a=parseInt(req.param("a"));
var b=parseInt(req.param("b"));
console.log(typeof a);
console.log(typeof b);

if(typeof a !=='number' || typeof b !=='number' ){
result={error: "Wrong format"};
res.send(JSON.stringify(result));
return;
}
var dejstvie=req.param("dejstvie");

switch(dejstvie){
case 'add':
result={dejstvie: 'plus', res: a+b};

break;
case 'sub':
result={dejstvie: 'minus', res: a-b};
break;
case 'mul':
result={dejstvie: 'po', res: a*b};
break;
case 'div':
result={dejstvie: 'deleno', res: a/b};
break;
default:
result={error: "No such action."};
break;
}

}catch(e){
result={error: e};
}

logResult(result, {a: a, b: b, dejstvie: dejstvie});
res.send("{\"result\": "+JSON.stringify(result)+"}");





});
app.get('/log/', function(req, res){
//res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
response=[];
try{
var sqlite3=require("sqlite3").verbose();
var db=new sqlite3.Database("EMSG.db");
db.serialize(/*function(){
db.run("CREATE TABLE "+
" if not exists "+
" LOG("+
"ID INTEGER PRIMARY KEY AUTOINCREMENT, "+
" txt text not null, "+
" request text not null,"+
" time datetime default current_timestamp"+
" );"
);



},*/
function(){
console.log("116");
db.each("SELECT * from LOG;",
function(err, row){
console.log(typeof err);
console.log(err);
if(err!= null){
console.log("119");
//console.log("problem: "+err);
response={error: err};
//console.log(res);

//res.send(JSON.stringify(response));
return;
}
//console.log(err);
console.log("131");
response.push(row);

}
,
function(){
console.log("136");
console.log(response);
console.log("before send");
res.send(JSON.stringify(response));
db.close();
}


);
//res.send(JSON.stringify(response));


}

);

}catch(error){
console.log({error : error});
res.send(JSON.stringify({error : error}));
}




});
var server=app.listen(8087, function(){
var host=server.address().address;
var port=server.address().port;
console.log("Listening at http://%s:%s", host, port);
});

 

2. Клиентско приложение.

<html>
<head>
<title>Елка</title>
<meta charset="utf-8">
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<style>
input[type="number"] {
max-width:30%;
min-width:20%;
}
.label-a{
min-width:10%;
max-width:15%;
}
</style>

</head>
<body>
<div class="panel panel-primary">
<div class="panel-heading">
Супер яка елка
</div>
<div class="panel-body">
<table class="table table-hover">
<tr>
<td ><div class="label-a">a</div></td><td><input type="number" class="form-control" id="input_a" name="input_a"></td>
<td ><div class="label-a">b</div></td><td><input type="number" class="form-control" id="input_b" name="input_b"></td>
</tr>
<tr>
<td colspan="2">
<select class="form-control" id="dejstvie" name="dejstvie">
<option value="add">събиране</option>
<option value="sub">изваждане</option>
<option value="div">деление</option>
<option value="mul">умножение</option>
</select>
</td>
<td colspan="2">
<input class="btn btn-primary" type="button" id="buton4e" name="buton4e" value="Калкулирай">
<input class="btn btn-primary" type="button" id="delete" name="delete" value="Изтрий">

</td>



</table>


</div>
</div>
<div class="panel panel-primary">
<div class="panel-heading">
Лог на действията
</div>
<div class="panel-body" id="logDiv">
</div>
<div class="panel-footer" id="logResult">
</div>
</div>

<script>
function aaaa(){
///console.log("Hello.");
var val_a=$("#input_a").val();
var val_b=$("#input_b").val();

var d=$("#dejstvie").val();

//console.log({a: val_a, b: val_b, d: d});
var url="http://localhost:8087/one/?a="+val_a+"&b="+val_b+"&dejstvie="+d;
//alert(url);
$.ajax({
url: "http://localhost:8087/one/?a="+val_a+"&b="+val_b+"&dejstvie="+d,
dataType: "text",
//jsonpCallback: "logResults",
error: function (request, error) {
alert("AJAX Call Error: " + error);
},
success: function (response) {
var resp = JSON.parse(response);
//alert(response);
//alert(resp.result.res);
$("#logResult").html("Result: "+resp.result.res);


},
});
///log results
$.ajax({
url: "http://localhost:8087/log/",
dataType: "text",
//jsonpCallback: "logResults",
error: function (request, error) {
alert("AJAX Call Error: " + error);
},
success: function (response) {
//$("#logResult").text("");
var resp = JSON.parse(response);
var new_text="";
for(i=0; i<resp.length; i++){
new_text+="<div>";
new_text+="request: "+resp[i].request+"<br/>";
new_text+="time: "+resp[i].time+"<br/>";
new_text+="</div>";
}
$("#logDiv").html(new_text);



//$("#logResult").text($("#logResult").text()+new_text);


},
});
};

function logResults(data){
//console.log(data);
alert(data);

};

$(document).ready(function(){
aaaa();
$("#delete").on('click', function(){
$.ajax({
url: "http://localhost:8087/delete/",
dataType: "text",

error: function (request, error) {
alert("AJAX Call Error: " + error);
},
success: function (response) {
$("#logResult").text("");
var res=JSON.parse(response);
if(typeof res.status == "undefined"){
$("#logDiv").html("Кофти");
}else if(res.status=="OK"){
$("#logDiv").html("OK");
}else{
$("#logDiv").html("Проблеми с базата данни");

}




//$("#logResult").text($("#logResult").text()+new_text);


},
});
});

$("#buton4e").on('click', function(){ aaaa();} );










});






</script>

</body>
</html>

За контакти:

ас. д-р инж. Георги Пашев

e-mail: georgepashev@uni-plovdiv.bg

http://gpashev.com

 

fulltext

Keywords

errorconsolefunctiontextresultclassjsonresponsedejstvieinputlogresultrequestsendstringifysqlite3paneloptionresphtmlalert