When you’re developing a REST API, and it’s not entirely clear how well your configuration of the client-side is working, it can be handy to get a server up quickly to log what it receives. In the Java servlet world, this might be done by introducing a filter class that inspects and logs all requests and responses. But if you don’t have the servlet itself setup yet, a faster way is to launch a NodeJs-based server locally.
If you’veĀ setup Eclipse IDE for debugging standalone JavaScript using NodeJs, then you can paste-in this as a new .js file and you’re almost home:
//Derived from http://stackoverflow.com/a/12007627 http = require('http'); //fs = require('fs'); port = 51100; host = '127.0.0.1'; server = http.createServer( function(req, res) { console.log("------------------------------"); var htmlPrefix = '<html> <body>', htmlSuffix = '<form method="post" action="http://'+ host +':'+ port +'"> String value to POST (type exit to quit): <input name="formSent" type="text"/> <input type="submit" value="Submit"/> </form> </body> </html>', html = null, //fs.readFileSync('index.html'); body = ''; var generateResponse = function() { html = html || htmlPrefix +'Received '+ req.method + (body ? ': '+body : '') + htmlSuffix; res.writeHead(200, {'Content-Type': 'text/html'}); res.end(html); if (body == "formSent=exit") { //console.log("Exiting process"); process.exit(code=0); } } if (req.method == 'POST') { req.on('data', function (data) { body += data; console.log("Partial body: " + body); }); req.on('end', function () { console.log("Body: " + body); generateResponse(); }); } else { //GET generateResponse(); } }); server.listen(port, host); console.log('Listening at http://' + host + ':' + port);
Once you see the console entry about “Listening…”, just open a browser tab to http://127.0.0.1:51100/.
If you can’t kill the process by entering exit
into the web form, then you can kill the node process from the commandline.