Skip to content

Instantly share code, notes, and snippets.

@ProfAvery
Created March 6, 2014 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ProfAvery/9383884 to your computer and use it in GitHub Desktop.
Save ProfAvery/9383884 to your computer and use it in GitHub Desktop.
Connect-ized form processing example with HTTP Basic
<% if (typeof message !== "undefined") { %>
<%= message %>
<% } %>
<form method="POST">
State:
<input type=text name="state"
<% if (typeof state !== "undefined") { %>
value="<%= state %>"
<% } %>
size="2" maxlength="2">
<input type="submit">
</form>
#!/usr/bin/env node
"use strict";
var fs = require("fs"),
util = require("util");
var connect = require("connect"),
_ = require("underscore");
var accounts = {
"user": "password",
"admin": "letmein"
};
var app = connect()
.use(connect.logger())
.use(connect.query())
.use(connect.bodyParser())
.use(connect.cookieParser())
.use(connect.cookieSession({secret: "s3cr3t"}));
// Anyone can request the favicon
app.use(function(req, res, next) {
if (req.url !== "/favicon.ico") {
return next();
}
res.writeHead(404);
res.end();
});
// Only logged-in users past this point
app.use(connect.basicAuth(function(username, password) {
return accounts[username] === password;
}));
app.use(function(req, res, next) {
if (req.method !== "POST") {
return next();
}
req.session.state = req.body.state;
req.session.message = util.format("Thanks, %s resident.", req.body.state);
res.writeHead(302, {
"Location": "/",
});
res.end();
});
app.use(function(req, res) {
res.writeHead(200, {
"Content-Type": "text/html"
});
fs.readFile("form.html", function(err, content) {
if (err) {
throw err;
}
var str = content.toString(),
template = _.template(str),
html = template(req.session);
res.write(html);
res.end();
});
});
app.listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment