Example of Get and Post in Express
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.
GET
We start off with index.js using mustache templating engine to reference the “form.html” template for our root route …
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 …
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 …
To obtain the posted values, we install body-parser middleware…
npm install body-parser --save
and require and use the module…
After the form is submitted, we console.log req.body to see what data we get…
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 …
The final output looks like this…