-
Notifications
You must be signed in to change notification settings - Fork 0
/
restfulBearJSON.js
64 lines (53 loc) · 1.72 KB
/
restfulBearJSON.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
var express = require('express');
var app = express();
var router = express.Router();
var bodyParser = require('body-parser')
// var urlencodedParser = bodyParser.urlencoded({ extended: false });
var bears = [{'id':0,'name':'pooh','weight': 211},
{'id':1, 'name':'vinnie','weight': 111}
]
var bearIndex=2;
app.use(express.static('public'))
router.route('/bears')
// get all the bears (accessed at GET http://localhost:8000/api/bears)
.get(function(req, res) {
res.json(bears);
})
// insert a new bear
.post(function(req, res) {
var bear = {};
bear.id = bearIndex++;
bear.name = req.body.name
bear.weight = req.body.weight
bears.push(bear);
res.json( {message: 'Bear created!'} )
})
// get a single bear
router.route('/bears/:bear_id')
.get (function(req,res) {
res.json(bears[req.params.bear_id])
})
.put (function(req,res) {
var id = req.params.bear_id
bears[id].name = req.body.name; // update the bears info
bears[id].weight = req.body.weight; // update the bears info
res.json({ message: 'Bear updated!' });
})
.delete (function(req,res) {
var id = req.params.bear_id
delete bears[id]
res.json({ message: 'Bear deleted!' });
})
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' })
});
// all of our routes will be prefixed with /api
app.use('/api', bodyParser.json(), router); //[use json]
//app.use('/api', bodyParser.urlencoded({ extended: false }), router);
app.use("*",function(req,res){
res.status(404).send('404 Not found');
// res.sendFile(__dirname + "/public/404.html");
});
app.listen(80, function() {
console.log("Server is running")
});