Skip to content

Instantly share code, notes, and snippets.

@ProfAvery
Last active August 29, 2015 13:56
Show Gist options
  • Save ProfAvery/9245300 to your computer and use it in GitHub Desktop.
Save ProfAvery/9245300 to your computer and use it in GitHub Desktop.
Form processing example from lecture
<% if (typeof message !== "undefined") { %>
<%= message %>
<% } %>
<form method="POST">
State:
<input type=text name="state"
value="<%= state %>" size=2 maxlength=2>
<input type="submit">
</form>
#!/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