-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
70 lines (54 loc) · 1.65 KB
/
index.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const express = require('express');
const app = express();
const port = process.env.PORT || 8081;
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const bodyParser = require('body-parser');
const path = require('path');
const url = '';
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(express.static('public'));
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
db.close();
});
function addPerson(person) {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
db.collection('demo').insertOne(person);
db.close();
});
}
function getAllPeople(callback) {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
db.collection('demo').find({}).toArray(function(err, docs){
console.log('find', docs);
callback(docs);
});
db.close();
});
}
app.post('/add', function(req, res) {
let person = req.body;
addPerson(person);
res.send('Added!');
});
app.get('/read', function (req, res) {
getAllPeople(function(people) {
//console.log('get', people);
res.send(people);
});
});
// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
getAllPeople(function(people) {
res.sendFile(path.resolve(__dirname, 'public/index.html'));
});
});
app.listen(port);
console.log('Listening on localhost:', port);