-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
68 lines (59 loc) · 1.81 KB
/
api.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
65
66
67
68
/**
* myapi.js
*
* @version 1.1 - updated for Express 4.x : April 2015
*
*
* DESCRIPTION:
* a "HELLO WORLD" server-side application to demonstrate running a node
* API Appserver on a Raspberry Pi to access IOs
* Uses the Express node packages.
*
*
* @throws none
* @see nodejs.org
* @see express.org
*
* @author Robert Drummond
* (C) 2013 PINK PELICAN NZ LTD
*/
var http = require('http');
var express = require('express');
var app = express();
// dummy input port values for our example
var inputs = [ { pin: '11', gpio: '17', value: 1 },
{ pin: '12', gpio: '18', value: 0 }
];
// ------------------------------------------------------------------------
// configure Express to serve index.html and any other static pages stored
// in the home directory
app.use(express.static(__dirname));
// Express route for incoming requests for a single input
app.get('/inputs/:id', function (req, res) {
// send an object as a JSON string
console.log('id = ' + req.params.id);
res.send(inputs[req.params.id]);
}); // apt.get()
// Express route for incoming requests for a list of all inputs
app.get('/inputs', function (req, res) {
// send an object as a JSON string
console.log('all inputs');
res.status(200).send(inputs);
}); // apt.get()
// Express route for any other unrecognised incoming requests
app.get('*', function (req, res) {
res.status(404).send('Unrecognised API call');
});
// Express route to handle errors
app.use(function (err, req, res, next) {
if (req.xhr) {
res.status(500).send('Oops, Something went wrong!');
} else {
next(err);
}
}); // apt.use()
// ------------------------------------------------------------------------
// Start Express App Server
//
app.listen(3000);
console.log('App Server is listening on port 3000');