-
Notifications
You must be signed in to change notification settings - Fork 1
Home
N Beaumont edited this page Jun 25, 2017
·
9 revisions
sampleNodeProject is a basic CRUD app built with node, mongodb, and express.
Today we wrote the server, created a mongo database on mlab.com, wrote two REST Apis, and began working on the front-end javascript and css.
We wrote a basic node server that listens on port 8081. We used express to set up the root route. When a GET request is sent to the root route, our server responds with hello world.
const express = require('express');
const app = express();
const port = process.env.PORT || 8081;
app.get('/', function (req, res) {
res.send('hello world');
});
app.listen(port);
console.log('Listening on localhost:', port);
Then we set up a mongo database (see the database section of this wiki).
We wrote an /add endpoint that will call our addPerson function it receives a POST request with an object in the body.
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();
});
}
app.post('/add', function(req, res) {
let person = req.body;
addPerson(person);
res.send('Added!');
});