###start => mkdir men-blog
- cd men-blog/
- git init
- git add -A
- git commit -m "first commit"
- git remote add origin https://github.com/username/men-blog-api.git
- git push -u origin master
- npm init
- git add .
- git commit -m "packages.json"
- git push -u origin master
- touch server.js
- subl .
- npm install mongoose --save
- npm install body-parser --save
- npm install express --save
- mkdir app
- cd app
- mkdir config
- cd config/
- touch routes.js
- cd ../..
- touch .gitignore
- touch Procfile
- git add .
- git commit -m "initial setup + server.js"
- git push origin master
- git checkout -b routes
- cd app
- mkdir models controllers
- mkdir models controllers
- cd models/
- touch article.js
- cd ..
- cd controllers/
- touch articles.js
- git add .
- git commit -m "adds models, controllers"
- cd ../..
- git add .
- git commit -m "builds schema for article"
- git checkout master
- git merge routes
- git push origin master
- nodemon
- git add -p
- git commit - m "continue codealong from here"
- git commit -m "continue codealong from here"
Finishing off this morning's setup:
-
finish routes :
var express = require('express'), apiRouter = express.Router(), articlesController = require('../controllers/articles'), Article = require('../models/article'); apiRouter.route('/articles') .post(function(req, res){ console.log(req.body); }) module.exports = apiRouter; -
fire up mongo:
$ mongod -
make a new db:
$ mongo> use men-blog// or whatever you named your dbalso if you want to make a change to your package.json you will be able to launch nodemon without sepcifying an entry point.
-
At this point you should be able to fire up your server
$ nodemon||$ nodemon server.jsand make a post request to /api/articles and see the req.body be logged out in the server
Let's refactor our .post logic so that it is in the controller:
app/config/routes.js:
```
var express = require('express'),
apiRouter = express.Router(),
articlesController = require('../controllers/articles'),
Article = require('../models/article');
apiRouter.route('/articles')
.post(articlesController.create);
module.exports = apiRouter;
```
app/controllers/articles.js:
```
//CONTROLLER
function create(req, res) {
console.log(req.body);
}
module.exports = {
create: create
};
```
should log you POST
Now lets make this controller ACTUALLY use our Article Schema
//CONTROLLER
var Article = require('../models/article');
function create(req, res) {
//Instantiate a new article using our awesome Schema:
var article = new Article(req.body);
//log it in the console, as before
console.log(req.body);
//save the Article / set up error handling
article.save(function(err) {
if (err) console.log('not able to create article b/c ' +err);
res.json({message: 'Article successfully created'});
})
}
module.exports = {
create: create
};