Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

using req.body and req.params and creating route middleware #14

Open
wants to merge 2 commits into
base: step-3
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// create a middleware function to catch and handle errors, register it
// as the last middleware on app



var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');

var lions = [{name: "mimi", pride: "wakanda", age: 3, gender: "male"}];
var id = 0;

var updateId = function(req, res, next) {
// fill this out. this is the route middleware for the ids
id = id++
next(id);
};

app.use(morgan('dev'))
app.use(express.static('client'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());


app.param('id', function(req, res, next, id) {
// fill this out to find the lion based off the id
// and attach it to req.lion. Rember to call next()
lion = id;

console.log({lion})
next();
});

app.get('/lions', function(req, res){
res.json(lions);
});

app.get('/lions/:id', function(req, res){
req.lion
let theLion = lions[lion];
console.log({theLion});
res.json(theLion || {});
});

app.post('/lions', updateId, function(req, res) {
var lion = req.body;
console.log({lion})
lions.push(lion);

res.json(lion);
});


app.put('/lions/:id', function(req, res) {
var update = req.body;
if (update.id) {
delete update.id
}

var lion = _.findIndex(lions, {id: req.params.id});
if (!lions[lion]) {
res.send();
} else {
var updatedLion = _.assign(lions[lion], update);
res.json(updatedLion);
}
});


app.use(function(err,req,res,next){
if(err){(console.log("error message"))}
res.status(500).send(err)
});

app.listen(3000);
console.log('on port 3000');
3 changes: 3 additions & 0 deletions server/server.js → server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ app.use(bodyParser.json());
app.param('id', function(req, res, next, id) {
// fill this out to find the lion based off the id
// and attach it to req.lion. Rember to call next()
id++;
console.log({id})
next();
});

app.get('/lions', function(req, res){
Expand Down