Let's copy our app folder to params-postable-app, and then install the body-parser middleware module:
$ cp -fr app params-postable-app
$ cd params-postable-app $ npm install --save body-parser
This example is for demonstration purposes only! Never place user input directly into HTML output in production without sanitizing it first. Otherwise, we make ourselves vulnerable to XSS attacks. See Guarding against Cross Site Scripting (XSS) in Chapter 8, Dealing with Security for details.
In the index.js file, we'll load the middleware and use it.
At the top of the index.js file we'll require the body parser middleware like so:
const bodyParser = require('body-parser')
Then we'll use it, just above the port assignment we'll add:
app.use(bodyParser.urlencoded({extended: false}))
We set extended to false because the qs module that provides the parsing functionality for bodyParse.urlencoded has options that could (without explicit validation) allow for a Denial of Service attack. See the Anticipating Malicious input recipe in Chapter 8, Dealing with Security.
Now in routes/index.js we'll alter our original GET route handler to the following:
router.get('/:name?', function (req, res) { const title = 'Express' const name = req.params.name res.send(` <html> <head> <title> ${title} </title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1> ${title} </h1> <p> Welcome to ${title}${name ? `, ${name}.` : ''} </p> <form method=POST action=data> Name: <input name=name> <input type=submit> </form> </body> </html> `) })
We're using Express' placeholder syntax here to define a route parameter called name. The question mark in the route string indicates that the parameter is optional (which means the original functionality for the / route is unaltered). If the name parameter is present, we add it into our HTML content.
We've also added a form that will perform a POST request to the /data route. By default it will be of type application/x-www-form-urlencoded , which is why we use the urlencoded method on the body-parser middleware.
Now to the bottom of routes/index.js we'll add a POST route handler:
router.post('/data', function (req, res) { res.redirect(`/${req.body.name}`) })
Now let's start our server:
$ node index.js
Then navigate our browser to http://localhost:3000 , supply a name to the input box, press the submit button and subsequently see our name in the URL bar and on the page.
This example is for demonstration purposes only! Never place user input directly into HTML output in production without sanitizing it first. Otherwise, we make ourselves vulnerable to XSS attacks. See Anticipating Malicious Input and Guarding against Cross Site Scripting (XSS) in Chapter 8, Dealing with Security.