Configuring the Express application
Now, to get started, we're going to need to install Express. We've already done that in the past, so over in the Terminal all we need to do is run npm i followed by the module name, which is express. We'll be using the most recent version, 4.16.2.
We're also going to be installing a second module, and we can actually type that right after the first one. There's no need to run npm install twice. This one is called the body-parser. The body-parser is going to let us send JSON to the server. The server can then take that JSON and do something with it. body-parser essentially parses the body. It takes that string body and turns it into a JavaScript object. Now, with body-parser, we're going to be installing version 1.18.2, the most recent version. I'm also going to provide the --save flag, which is going to add both Express and body-parser to the dependencies section of package.json:
npm i express@4.16.2 body-parser@1.18.2 --save
Now, I can go ahead and fire off this request, installing both modules, and over inside of server.js, we can start configuring our app.
First up, we have to load in those two modules we just installed. As I mentioned previously, I like to keep a space between local imports and library imports. I'm going to use a variable called express to store the Express library, namely require('express'). We're going to do the same thing for body-parser with a variable called bodyParser, setting it equal to the return result from requiring body-parser:
var express = require('express'); var bodyParser = require('body-parser');
var {mongoose} = require('./db/mongoose');
var {Todo} = require('./models/todo');
var {User} = require('./models/user');
Now that we can set up a very basic application. We're going to make a variable called app; this is going to store our Express application. I'm going to set this equal to a call to express:
var {User} = require('./models/user');
var app = express();
And we're also going to call app.listen, listening on a port. We will be deploying this to Heroku eventually. For now though, we're going to have a local port, port 3000, and we'll provide a callback function that's going to fire once the app is up. All we're going to do is use console.log to print Started on port 3000:
var app = express();
app.listen(3000, () => { console.log('Started on port 3000'); });