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 //ANY POST request to /processForm we expect will be sending us HTML form data with 2 fields named "to" and "say"
//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 +
will produce
|
res object
|
STEP 4: Lets run it
-
assuming you have your app setup
type> node index.js in command window AND got to browser localhost:3000


