পৃষ্ঠাসমূহ

.

Search Your Article

Total Pageviews

Friday, February 17, 2017

ExpressJS - Form data

Forms are an intergral part of the web. Almost every website we visit offers us forms that submit or fetch some information for us. To get started with forms, we will first install the body-parser(for parsing JSON and url-encoded data) and multer(for parsing multipart/form data) middleware. To install these, go to your terminal and use:

npm install --save body-parser multer
Replace your index.js file contents with the following code:
var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer(); 
var app = express();

app.set('view engine', 'pug');
app.set('views', './views');

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'));

app.post('/', function(req, res){
    console.log(req.body);
    res.send("recieved your request!");
});

app.listen(3000);
The new things we are doing here are importing the body parser and multer. We are using body parser for parsing json and x-www-form-urlencoded header requests, while we use multer for parsing multipart/form-data.
Let us create a html form to test this out! Create a new view called form.pug with the following code:
html
    head
        title Form Tester
    body
        form(action="/", method="POST")
            div
                label(for="say") Say: 
                input(name="say" value="Hi")
            br
            div
                label(for="to") To: 
                input(name="to" value="Express forms")
            br
            button(type="submit") Send my greetings
Run your server using:
nodemon index.js
Now go to localhost:3000/ and fill the form as you like, and submit it. You'll get the response as:
Response to form submission Have a look at your console, it'll show you the body of your request as a JavaScript object. For example:
Console output for form The req.body object contains your parsed request body. To use fields from that object, just use them like normal JS objects.
This is just one way to send a request. There are many other ways, but those are irrelevent to cover here, because our Express app will handle all those requests in the same way. To read more about different ways to make a request, have a look at this page.

No comments:

Post a Comment