*** 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
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>
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 separatorsapp.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
The For example:
But you could just as well have:
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 +
|
res object
|
assuming you have your app setup
type> node index.js in command window AND got to browser localhost:3000