Skip to content

Instantly share code, notes, and snippets.

@ahdinosaur
Created March 21, 2016 21:35
Show Gist options
  • Save ahdinosaur/21564b990218352d7f3e to your computer and use it in GitHub Desktop.
Save ahdinosaur/21564b990218352d7f3e to your computer and use it in GitHub Desktop.
live lecture 16-03-22
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