How to receive post parameter in Express.js ?
Express is a small framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing; it adds helpful utilities to Node.js’s HTTP objects; it facilitates the rendering of dynamic HTTP objects. Express.js provides various types of methods for handling different types of incoming requests such as get, Post, etc from the client-side. In this article, we will discuss how to receive post parameter in express.js.
POST parameter can be received from a form using express.urlencoded() middleware and the req.body Object. The express.urlencoded() middleware helps to parse the data that is coming from the client-side.
express.urlencoded( [options] )
Parameter: The options parameter contains various properties like extended, inflate, limit, verify, etc.
Return Value: It returns an Object.
Example: Let’s discuss each step one by one to receive post parameters in the express.js
Step 1: Create an “app.js” file and initialize your project using npm.
Step 2: Create an “index.html” file and install the express package using npm.
npm install express
Step 3: Now let us first code the “index.html” file. In it, we make a form and submit that form as method “POST” to the ‘/submit‘ route which we would declare later in the “app.js” file.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> </head> <body> <!-- Action to the same route as in app.post() method --> <form action="/submit" method="post"> Name: <input type="text" name="name"> <br><br> Email: <input type="email" name="email"> <br><br> Gender: <br> <input type="radio" name="gender" id="male"> Male <br> <input type="radio" name="gender" id="female"> Female <br> <input type="radio" name="gender" id="private"> Don't want to disclose <br><br> Hobbies: <br> <input type="checkbox" name="painting" id="painting"> Painting <br> <input type="checkbox" name="dancing" id="dancing"> Dancing <br> <input type="checkbox" name="singing" id="singing"> Singing <br> <br> <input type="file" name="file" id=""> <br> <br> <button type="submit">Submit</button> </form> </body> </html>