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:
Let us create a html form to test this out! Create a new view called form.pug with the following code:
Have a look at your console, it'll show you the body of your request as a JavaScript object. For example:
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.
npm install --save body-parser multerReplace 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 greetingsRun your server using:
nodemon index.jsNow go to localhost:3000/ and fill the form as you like, and submit it. You'll get the response as:
Have a look at your console, it'll show you the body of your request as a JavaScript object. For example:
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