Skip to content

Instantly share code, notes, and snippets.

@joe-oli
Created November 17, 2018 08:24
Show Gist options
  • Save joe-oli/49cb4382068d5d5f9ebada650a6f8b37 to your computer and use it in GitHub Desktop.
Save joe-oli/49cb4382068d5d5f9ebada650a6f8b37 to your computer and use it in GitHub Desktop.
basic node.js server (no express) showing GET and POST
/* ============= basicServer101.js ============== */
/* shows
- handling Body in a POST (or PUT) request;
- two http-request handlers can be hooked up to the same event; both get called one after the other... (just experimenting... we could use one handler with if-then inside it)
USAGE:
at a cmd prompt enter:
>node basicServer101
then at a Browser enter:
http://localhost:8080/
*/
const http = require('http');
//create server...
const myServer = http.createServer(); //LHS is called an EventEmitter
//then hookup two request handlers in succession... BOTH WILL BE HIT on every request, but if-condition based on http-method decides if they will do anything...
//first-handler... for GET
myServer.on('request', function(req,res) { //add handler to EventEmitter
const { method, url, headers} = req;
//When a http-request hits the server, examine the URL and method, so that appropriate actions can be taken...
if (method === 'GET') {
console.log('========> GET handler at...' + new Date().toISOString())
/*
console.log("method:", method)
console.log("url:", url) //variation test: add a queryString to the Browser url. e.g. http://localhost:8080/?key1=fax&key2=off; THEN YOU SHOULD SEE url: /?key1=fax&key2=off
console.log("headers.host:", headers.host)
console.log("headers.user-agent:", headers["user-agent"]) //<============ due to hyphen - in propname, extract using Array[syntax] instead of Object.Prop)
*/
res.writeHead(200, {'Content-Type' : 'text/html'});
res.write('<h2>hello World!</h2>');
res.write('<div>... from a basic node server:-)</div>');
res.write('<p>&nbsp;</p>');
// fields on page to post data back to server,,,
res.write('<form method="POST" action="/">')
res.write('<input type="text" name="txtfirstName" value="joe" />')
res.write('<br />')
res.write('<input type="text" name="txtlastName" value="oli" />')
res.write('<p>&nbsp;</p>')
res.write('<input type="submit" name="btnSubmit" />')
res.write('</form>')
res.end();
/* serve following page...
<html>
<head></head>
<body>
<h2>hello World!</h2>
<div>... from a basic node server:-)</div>
<p>&nbsp;</p>
<form method="POST" action="/">
<input type="text" name="txtfirstName" value="joe" /><br>
<input type="text" name="txtlastName" value="oli" />
<p>&nbsp;</p>
<input type="submit" name="btnSubmit" />
</form>
</body>
</html>
*/
}
});
//second-handler.. for POST
myServer.on('request', function(req,res) { //add handler to EventEmitter
const { method, url, headers} = req;
//When a http-request hits the server, examine the URL and method, so that appropriate actions can be taken...
if (method == 'POST') {
console.log('========> POST handler at...' + new Date().toISOString())
let body = []; let bodyAsString = "";
req.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
bodyAsString = Buffer.concat(body).toString();
// at this point, `bodyAsString` has the entire request body stored in it as a string
console.log(bodyAsString) //txtfirstName=joe&txtlastName=oli&btnSubmit=Submit
//NOW serve a new page ...
res.writeHead(200, {'Content-Type' : 'text/html'});
res.write('<h3>you submitted:</h3>');
//extract what was posted...
let keyValArr = bodyAsString.split("&");
keyValArr.map( (kvp, idx) => {
let keyVal = kvp.split('=');
res.write('<div>')
res.write('<label style="color:green">'+keyVal[0]+':</label>')
res.write('<span>'+keyVal[1]+'</span>')
res.write('</div>')
})
res.write('<p>&nbsp;</p>');
res.write('<a href="/">Go back</a>') //make a GET request using link
//or ALT use js...
res.write('<p>&nbsp;</p>');
// res.write('<button type="button" onclick="alert(\'fax off\')">Go back</button>')
res.write('<button type="button" onclick="window.location.href= \'/\'">Go back</button>')
res.write('<p>&nbsp;</p>');
res.end();
/* serve following page...
<html>
<head></head>
<body>
<h3>you submitted:</h3>
<div><label style="color:green">txtfirstName:</label><span>joe</span></div>
<div><label style="color:green">txtlastName:</label><span>oli</span></div>
<div><label style="color:green">btnSubmit:</label><span>Submit</span></div>
<p>&nbsp;</p><a href="/">Go back</a>
<p>&nbsp;</p><button type="button" onclick="window.location.href= '/'">Go back</button>
<p>&nbsp;</p>
</body>
</html>
*/
}).on('error', (err) => {
console.error(err.stack); // This prints the error message and stack trace to `stderr`.
//NB: it's important to be listening for error events on the stream, else the error will be thrown which may crash your Node.js program.
});
}
});
myServer.listen(8080, function() {
console.log('nodejs server is listening on port 8080...');
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment