Our first assignment in Connected Devices was to make a basic web server with node.js and express.js, with three end points.
I had originally tried to make this a musical project, where different musical sequences played on the server. The *music* part did not pan out (a fight for another day!) But the node server with endpoints exists.
One GET request gets the main webpage: /index.html
Another GET will tell the user the current sequence: /currentSequence
And a POST method via webpage sets the sequence: /readform
All of the functionality is pretty basic right now, but I’m hoping this can be the template for something more complicated in the future.
Here is the code currently:
/* Starting with the four line server example:
from Tom Igoe examples:
https://github.com/tigoe/NodeExamples/blob/master/FourLineServer/server.jscombined with express guide on routing:
https://expressjs.com/en/guide/routing.htmlspecial thanks to Steph Koltun for lots of help
*/var express = require(‘express’); //include express
var server = express();
var bodyParser = require(‘body-parser’); //create a servervar currentSequence = “sequence1”;
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({extended:false}));//server.use(‘/’,express.static(‘public’)); //serve static files from /public
server.listen(8080); //start the server
server.get(‘/’,function(req,res){
console.log(‘got a GET request’);
//res.sendFile(‘index.html’);
})server.get(‘/index.html’,function(req,res){
console.log(‘got a GET request’);
res.sendFile(‘/public/index.html’, {“root”: __dirname});
//I had problems getting the HTML file,
//wound up finding this “dirname” trick here:
// https://codeforgeek.com/2015/01/render-html-file-expressjs/})
server.get(‘/currentSequence’,function(req,res){
console.log(‘got a GET request’);
res.send(“Current Sequence is: ” + currentSequence);
})server.post(‘/readform’,function(req,res){
//console.log(req.body);
console.log(req.body.contact);var incomingRequest = req.body.contact;
if (incomingRequest == “sequence1”){
currentSequence = incomingRequest;
res.send(“Setting to ” + currentSequence)
}
if (incomingRequest == “sequence2”){
currentSequence = incomingRequest;
res.send(“Setting to ” + currentSequence)
}
if (incomingRequest == “sequence3”){
currentSequence = incomingRequest;
res.send(“Setting to ” + currentSequence)
}})