NodeJS, Express and POST
By Dan Baker, published 2010-09-23
We are going to walk through the steps of how to get POST variables -- the data posted to the server via an http form. STEP 1: Create a new app.js with Expressvar PORT = 9000; // port# to run this server/app on var express = require("express"); var app = express.createServer(); // special handling of the root folder app.get("/", function(req, res){ res.writeHead(200, {'Content-Type': 'text/html'}); res.write('Welcome<br>'); res.write('<a href="/login">Please login</a>'); res.end(); }); // startup this server app.listen(PORT); console.log("Express server started on port %s", app.address().port); This is the "basic" Express server. It only serves a single page (the root, or home, page). If you run this (node app.js) and visit localhost:9000, you should see the "Welcome" page. Visiting the login page will not work at this step. STEP 2: Add a handler for the \login page // special handling for the "login" process // This is called from a normal "get" request to the "\login" page app.get("/login", function(req, res){ res.writeHead(200, {'Content-Type': 'text/html'}); res.write('Login<br>'); res.write('<form method="POST" action="/login">'); res.write('<input type="text" name="user"><br>'); res.write('<input type="password" name="pass"><br>'); res.write('<input type="submit" name="login" value="Login">'); res.write('</form>'); res.end(); }); When this app.js is run, you can successfully visit the login page. If you submit the page, you will get a page-not-found error. We'll fix that next step. STEP 3: Add a handler for the POST to the \login page // special handling for the "login" process // This gets called when a POST happens to the "\login" page app.post("/login", function(req, res){ var user = req.param("user"); var pass = req.param("pass") console.log("user="+user); console.log("pass="+pass); res.writeHead(200, {'Content-Type': 'text/html'}); res.write('Thank you, '+user+', you are now logged in.'); res.end(); }); This step adds a special handler for the form data that is POSTed to the \login page. When you run it, you'll notice that the user and pass variables are undefined. We need to tell Express to process the form data. STEP 4: Ask Express to process the form data NOTE: Replace the top of your file with this new code, which configures Express. var PORT = 9000; // port# to run this server/app on var express = require("express"); var app = express.createServer(); app.configure(function(){ app.use(express.bodyDecoder()); }); We have to configure Express to use a body decoder. The form data comes back in a special area of the http response. This new configuration When you run this finished app, you can visit the visit login page, fill in the form, and submit it. You should get two lines on the console showing the username and password entered, and also a page returned with their username showing.