I have this code snippet.
function handleRequest(req, res)
{
req.on('data', parseInput);
res.write(generateInputform());
}
http.createServer(handleRequest).listen(port, ipAddress);
The req.on callbacks parseInput and does literally what the function's called, it parses the input and sets pins and such. Afterwards another input form is generated and presented to the user.
However, node.js generates the input first and then parses the input... This means the user has to refresh the page to reflect the given commands. Parsing input works, I can see the pins toggle on submit with my logic analyzer.
I seem to be stuck in a rut as I cannot find a simple solution to this answer. The ones that show promise deal with asynchronous delaying which I'd rather avoid.
Perhaps someone can shed a light on this issue?
Here's the complete handleRequest.
function handleRequest(req, res)
{
switch( req.url )
{
case "/markings.css" :
res.writeHead(200, {'Content-Type': 'text/css'});
res.end("Literally nothing right now");
break;
case "/json" :
res.writeHead(200, {'Content-Type': 'text/json'});
res.end(encapsulator(J17_1, J18_1, J19_14, J20_14));
break;
case "/index":
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(getHTML());
break;
case "/":
// show the user a simple form
console.log("[200] " + req.method + " to " + req.url);
res.writeHead(200, "OK", {'Content-Type': 'text/html'});
switch( req.method )
{
case 'POST':
//Problems between here
req.on('data', parseInput);
res.write(generateInputform());
//And here
console.log("Done");
res.end();
break;
case 'GET':
console.log("User probably refreshed page without entering anything useful");
res.write(generateInputform());
console.log("Done");
res.end();
break;
default:
console.log("?");
res.end();
break;
}
//res.end();
break;
default:
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<!DOCTYPE html>\r\n<html>\r\n<body>\r\n404, that means trouble.<br><a href="http://' +
ipAddress + ':' + port + '">Go back to the index</a></body></html>');
break;
}
}
Edit:
Answer found here. Make a blocking call to a function in Node.js required in this case?
New handleRequest
req.on('data', parseInput);
req.on('end', function()
{
res.write(generateInputform());
console.log("Done");
res.end();
});