I am Hack Sparrow
Captain of the Internets.

Form Handling / Processing in Express.js

Depending on where you come from, you either call it form processing or form handling, but they mean the same thing - doing stuff to things submitted through an HTML form. In this tutorial I'll show you how to handle all aspects of form processing in Express.js.

Express.js is the most popular web development framework as of this writing. There are two major aspects to HTML forms: i. GET requests, ii. POST requests. Let's see how we deal with them in Express.

Handle / Process GET requests in Express


There are two ways of passing parameters to an Express application: i. Using named placeholders, ii. GET parameters.

i. Named Placeholders

Named placeholders are defined in Express routes (very likely in the app.js file), and use URL fragments for relaying information to the app. A named placeholder might be defined and accessed this way in Express:

app.get('/user/:id', function(req, res) {
res.send('user ' + req.params.id);
});

ii. GET Parameters

Another method of sending information to an app in the URL is to pass them via GET parameters.

If this is the URL

http://localhost/books?category=biographies&type=paperback

you access the GET parameters in Express, this way:

console.log('Category: ' + req.query['category']);
console.log('Type: ' + req.query['type']);

Handle / Process POST requests in Express


The POST request method also has two aspects to it: i. text data, ii. file uploads. Let's see how they are handled in Express.

i. Text Data

All default Express applications are ready to handle text POST requests using the bodyParser middleware. Look for app.use(express.bodyParser()) in app.js, if you see that, you are good to go.

If your form looks like this:

<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>

you can access the POST submitted text data this way:

console.log('Username: ' + req.body.username);
console.log('Password: ' + req.body.password);

ii. File Uploads

This part of the article is not recommended if you are working with the latest version of Express. Read this instead.

File uploads in Express is not that straightforward as of this writing. But it isn't that complicated either, you just need to do a few things and you'll be all set up to handle file uploads too.

First of all you'll need to install connect-form.

$ npm install connect-form
connect-form@0.2.1 ./node_modules/connect-form
└── formidable@1.0.8

You might have read/seen somewhere that you can use node-formidable too for uploading files. Confused whether to use node-formidable or connect-form? Let all confusion be cleared, for connect-form is nothing but node-formidable itself! Yes, connect-form is just an Express-friendly wrapper on top of node-formidable.

After you have installed connect-form, you need to make some changes to app.js. Require the connect-form module, and pass a form object to express.createServer.

var form = require('connect-form');
var app = module.exports = express.createServer(form({ keepExtensions: true, uploadDir:'./uploads' }));

The uploadDir parameter is used to specify where we want the files to be uploaded to. For more details about connect-form, visit the connect-form GitHub page.

So here is the updated HTML form:

<form method="post" enctype="multipart/form-data" action="/file-upload">
<input type="text" name="username">
<input type="password" name="password">
<input type="file" name="thumbnail">
<input type="submit">
</form>

Make sure method is set to post and enctype to multipart/form-data, else file uploads just won't work. It is very important to note that once you have set your form to multipart/form-data, you will no longer be able to access the post data from req.body!


Here is the Express route and an example code to handle the above form:

app.post('/file-upload', function(req, res, next) {
req.form.complete(function(err, fields, files) {
if (err) { next(err); }
else {
console.log(fields);
console.log('---------------');
console.log(files);
res.redirect(req.url);
}
});
});

All the POST text fields and values are available in the fields object of the req.form.complete callback object, and all the files in the files object. Since you have the references to the POST objects now, process them whatever way suits you.

With this we come to the end of form handling / processing tutorial in Express. If you have any questions, opinions, need examples; ping me in the comments. All the best!

4 Responses to “Form Handling / Processing in Express.js”

  1. tbeseda says:

    Thanks for the explanation, particularly related to connect-form vs. formidable.

  2. tbeseda says:

    Looking into it some more, connect-form is deprecated according to the README on github. formidable is baked into connect, and therefor express.

    Uploaded files are available on the files key of the req object where the name of the file field is the key: request.files.myFile

  3. Captain says:

    Thanks bro, I have updated the article with a notice, and a link to the new post which shows the recommended way to handle file uploads in Express.

  4. Kartheek says:

    Thanks bro.

Make a Comment