Express Form Processing through use of Middleware

 

STEP 1: install body-parers and multer packages

*** assumming you have already created a basic express applicaiton project *****

 install the body-parser(for parsing JSON and url-encoded data) and multer(for parsing multipart/form data) middleware.

 

GO to your application directory and type

npm install --save body-parser multer

 

STEP 2: create a form (here using ejs) -- and I am putting it in the views/pages directory

form.ejs file


<!DOCTYPE html>
<html>
<head>
               Testing Form data
   </head>
<body>
                 hello <br><br>
<form action="/processForm", method="POST")
   <div>
    <label> Say</label>
    <input type="text" name="say" value="hi"> 
    <br/>
    <label> TO:</label>
    <input type="text" name="to"  value="express forms"> 
    <input type="submit" value="send greetings"> 
   </div>
</form>
            
</body>
</html>
            

 

STEP 3: create an index.js file that will use body-parser and multer and read in data from the form

 

index.js

/**
                   simple index to use following middleware
 bodyparser= for parsing JSON and url-encoded data
 multer = for parsing multi-part/form data
 */
 var express = require('express');
 var bodyParser = require('body-parser');
 var multer = require('multer');
 var path = require ('path'); //to work with separtors on any OS including Windows
 var upload = multer(); 
 var app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname + '/views'));  //path.join -resolve OS file separators
app.use(express.static(path.join(__dirname + '/public')));
                 
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(upload.array()); // for parsing multipart/form-data app.use(express.static('public'));
//ANY POST request to /processForm  we expect will be sending us HTML form data with 2 fields named "to" and "say"
// printout to the response some of this body data
app.post('/processForm', function(req, res){ console.log(req.body); var body = JSON.stringify(req.body); var params = JSON.stringify(req.params); var value_tofield_formdata = req.body.to; var value_sayfield_formdata = req.body.say; res.send("recieved your request!</br>" + "parameters: " + params + "</br>URL:" + req.url
+ "<br>body: " + body + "<br>the -to- form field = " + value_tofield_formdata + "<br> the -
say- form field = " + value_sayfield_formdata); });
//ANY GET request to /form render the form.ejs file from STEP 2
app.get('/form', function(req, res){
       console.log(req.body);
       res.render('pages/form')
  });
app.listen(3000);
 

 

LETs REVIEW A LITTLE before running it

req object

  • req.params.name_of_param

The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, the object is always referred to as req (and the HTTP response is res) but its actual name is determined by the parameters to the callback function in which you’re working.

For example:

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

But you could just as well have:

app.get('/user/:id', function(request, response) {
    response.send('user ' + request.params.id);
  });
  • req.baseUrl, req.body, req.cookies (req.cookies.name_of_cookie), req.hostname, req.path, etc see documentation

NOTE: if you want to see the body of the request for printing it out do the following

console.log(JSON.stringify(req.body));

 

if you do the following will brint out a "Object"

console.log(req.body);

 

For example the following handler code:

var body = JSON.stringify(req.body);
 var params = JSON.stringify(req.params);
 res.send("recieved your request!</br>" + "parameters: " + params +
"</br>URL:" + req.url + "body: " + body);

 

will produce

  • req.body

    Contains key-value pairs of data submitted in the request body.

res object

 

  • res.render, res.send, res.cookie, res.redirect, and many more

 

 

STEP 4: Lets run it

 

 

© Lynne Grewe