English 中文(简体)
ExpressJS - Form Data
  • 时间:2024-12-22

ExpressJS - Form data


Previous Page Next Page  

Forms are an integral 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 the body-parser and multer, 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.get( / , function(req, res){
   res.render( form );
});

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

// for parsing apppcation/json
app.use(bodyParser.json()); 

// for parsing apppcation/xwww-
app.use(bodyParser.urlencoded({ extended: true })); 
//form-urlencoded

// for parsing multipart/form-data
app.use(upload.array()); 
app.use(express.static( pubpc ));

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

After importing the body parser and multer, we will use the body-parser for parsing json and x-www-form-urlencoded header requests, while we will use multer for parsing multipart/form-data.

Let us create an html form to test this out. Create a new view called form.pug with the following code −

html
html
   head
      title Form Tester
   body
      form(action = "/", method = "POST")
         span
            label(for = "say") Say:
            input(name = "say" value = "Hi")
         br
         span
            label(for = "to") To:
            input(name = "to" value = "Express forms")
         br
         button(type = "submit") Send my greetings

Run your server using the following.

nodemon index.js

Now go to localhost:3000/ and fill the form as you pke, and submit it. The following response will be displayed −

Response to form submission

Have a look at your console; it will show you the body of your request as a JavaScript object as in the following screenshot −

Console output for form

The req.body object contains your parsed request body. To use fields from that object, just use them pke normal JS objects.

This is the most recommended way to send a request. There are many other ways, but those are irrelevant 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.

Advertisements