Example of Get and Post in Express

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In this tutorial, we will create a form which user post their meal preferences to another page so that we can see how to implement Express’s get and post routing methods.

meal form

GET

We start off with index.js using mustache templating engine to reference the “form.html” template for our root route …

index page

The app.get indicates that at the root route, render the form.

The Form

And our form.html in the views folder looks like this …

the form

Yes, we should use label tags and also add “required” attributes.  But we left them out to keep the tutorial simple.

POST

Now when the user hits submit, it goes to process_form which we will create using the post method …

handle-post

To obtain the posted values, we install body-parser  middleware…

npm install body-parser --save

and require and use the module…

example using bodyparser

After the form is submitted, we console.log req.body to see what data we get…

data retreived

If user did not select a meal_type, it will not show up in the data.  So we have to account for that.  Note how the checkboxes comes in as array values if user checkmarks both options.  But it is a single string if one checkbox is checked.

The error checking and construction of the output can be like this …

validation code

The final output looks like this…

final output