-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
46 lines (39 loc) · 1.15 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//Import requiered packages
const express = require('express');
const {Client} = require('pg');
//Create the conection to the postgres server
const client = new Client({
connectionString: process.env.DATABASE_URL
});
client.connect();
//Create the express app
const bodyParser = require('body-parser');
const app = express();
// parse application/json
app.use(bodyParser.json());
//Handle a post request at /query
app.post('/query', (req, res) => {
res.setHeader('Content-Type', 'application/json');
console.log("Receiving request");
if(req.body.query) {
console.log(req.body.query);
client.query(req.body.query, (err, r) => {
if (err) {
res.end({"error": "Unexpected error ocurred"});
return
}
rows = [];
for(let row of r.rows){
rows.push(row);
}
response = JSON.stringify(rows);
console.log(response);
res.end(response);
});
}
});
const port = process.env.PORT || 8080;
//Start listening
const server = app.listen(port, function () {
console.log("App listening at ${host}")
});