SERVER SIDE:
console.log('Server-side code running');
const express = require('express');
const postgreSQLclient = require('pg-promise')({}); //Created an instance of postgresql
const app = express();
app.use(express.static('public'));
let db;
//url of your postgresql database in the string in next line
const url = 'postgresql://localhost:5432/clicks';
db = postgreSQLclient (url); //Connecting to the database
// start the express web server listening on 8080
app.listen(8080, () => {
console.log('listening on 8080');
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
var id = 0; //A variable to store the id value. Used in search and update on database below
//Update click value by adding 1 in database for id = skylar, then return click value
app.post('/clicked', (req, res) => {
db.one('UPDATE clicks set click=click+1 WHERE myId=$1 returning *',id)
.then(function (data) {
res.send(data.click);
})
.catch(function (error) {
return error;
});
});
//Select click value from database for id = skylar, then return click value
app.get('/clicks', (req, res) => {
db.one('SELECT * from clicks WHERE myId = $1', id)
.then(function (data) {
res.send(data.click);
})
.catch(function (error) {
return error;
})
});
CLIENT SIDE:
console.log('Client-side code running');
const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
console.log('button was clicked');
fetch('/clicked', {method: 'POST'})
.then(function(response) {
if(response.ok) {
console.log('click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
});
setInterval(function() {
fetch('/clicks', {method: 'GET'})
.then(function(response) {
if(response.ok) return response.json();
throw new Error('Request failed.');
})
.then(function(data) {
document.getElementById('counter').innerHTML = `Button was clicked ${data.length} times`;
})
.catch(function(error) {
console.log(error);
});
}, 1000);
HTML PAGE:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Node + Express + MongoDb</title>
<style>
h1 {
text-align: center;
}
p {
text-align: center;
}
.button-center {
text-align: center;
padding-top: 50px;
}
#myButton {
height: 50px;
width: 150px;
border: 2px solid black;
}
</style>
</head>
<body>
<h1 id="counter">Loading button click data.</h1>
<div class="button-center">
<button id="myButton">The Button</button>
</body>
<script src="client.js"></script>
</html>