Created
March 21, 2016 21:35
-
-
Save ahdinosaur/21564b990218352d7f3e to your computer and use it in GitHub Desktop.
live lecture 16-03-22
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express') | |
var bodyParser = require('body-parser') | |
/* | |
RESTful HTTP API routing | |
example: `/things` resource | |
GET /things -> [{ id: 0, name: "computer" }, { id: 1, name: "javascript" }] | |
POST /things { name: "desk" } -> { id: 2, name: "desk" } | |
GET /things/2 -> { id: 2, name: "desk" } | |
PUT /things/2 | |
DELETE /things/2 | |
methods: | |
- GET | |
- POST (create) | |
- PUT (update) | |
- PATCH (update) | |
- DELETE | |
*/ | |
var app = express() | |
app.use(bodyParser.json()) | |
var things = [{ | |
id: 0, name: "computer" | |
}, { | |
id: 1, name: "javascript" | |
}] | |
app.get('/things', function (req, res) { | |
res.send(things) | |
}) | |
var id = 2 | |
app.post('/things', function (req, res) { | |
var newThing = req.body | |
newThing.id = id | |
things.push(newThing) | |
res.send(newThing) | |
id += 1 // increment id for next thing | |
}) | |
app.get('/things/:id', function (req, res) { | |
// TODO re-write with lodash.find | |
var filteredThings = things.filter(function (thing) { | |
return thing.id == req.params.id | |
}) | |
res.send(filteredThings[) | |
}) | |
app.listen(5000, function () { | |
console.log('server listening on port 5000') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment