Last active
August 29, 2015 13:56
-
-
Save ProfAvery/9245300 to your computer and use it in GitHub Desktop.
Form processing example from lecture
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<% if (typeof message !== "undefined") { %> | |
<%= message %> | |
<% } %> | |
<form method="POST"> | |
State: | |
<input type=text name="state" | |
value="<%= state %>" size=2 maxlength=2> | |
<input type="submit"> | |
</form> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
var http = require("http"), | |
fs = require("fs"), | |
querystring = require("querystring"), | |
_ = require("underscore"); | |
function parseCookies(header) { | |
var cookies = { | |
state: "CA", | |
message: undefined | |
}; | |
if (header) { | |
_.each(header.split("; "), function(cookie) { | |
var q = querystring.parse(cookie); | |
_.each(q, function(key, value) { | |
cookies[value] = key; | |
}); | |
}); | |
} | |
return cookies; | |
} | |
http.createServer(function(req, res) { | |
console.log(req.method, req.url); | |
if (req.url === "/favicon.ico") { | |
res.writeHead(404); | |
res.end(); | |
return; | |
} | |
if (req.method === "POST") { | |
var payload = ""; | |
req.on("data", function(chunk) { | |
payload += chunk; | |
}); | |
req.on("end", function() { | |
var q = querystring.parse(payload); | |
res.writeHead(302, { | |
"Location": "/", | |
"Set-Cookie": [ | |
"state=" + q.state, | |
"message=Thanks" | |
] | |
}); | |
res.end(); | |
}); | |
} else { | |
res.writeHead(200, { | |
"Content-Type": "text/html" | |
}); | |
fs.readFile("form.html", function(err, content) { | |
if (err) throw err; | |
var header = req.headers.cookie, | |
cookies = parseCookies(header), | |
str = content.toString(), | |
template = _.template(str), | |
html = template(cookies); | |
console.log(cookies); | |
res.write(html); | |
res.end(); | |
}); | |
} | |
}).listen(8080); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment