Getting Form Data in Node.js

NodeJS Form Data Thumbnail

Getting form data in Node.js is important in order to create functionalities that require getting the data from the users. 

For example, when we create a to-do list application it is required to get the to-do as input from the users, similarly, when creating a register page it is required to get the username and password of the user trying to create their account. 

For this we can create an HTML file with a form and send that file to the user, we have a separate article where we provide the step-by-step guide to send an HTML file in Node.js.

After sending the file we somehow have to get that entered data in the input field of the form of the HTML file.

In the early stage of the express module, we have to use a separate module “body-parser” in order to handle form data. The Express v4.16.0 onwards includes a built-in middleware function for the same purpose, this middleware is itself based on “body-parser” so it no longer needs to install manually.

Fetch Form Data in Node.js

Let’s create a simple application to see how to fetch from data in Node.js.

Create a folder containing two files “app.js” and “index.js”  & open it inside the Code Editor.

Project Structure

Then in the terminal, type the following commands

npm init -y

This will initialize the Node Packages manager, by which we can install any Node.js framework.

npm i express

this will install express as a module in your application.

Inside the “index.html” file create an h1 tag with a form. Inside the form, specify the action as “/” and the method as “post” which is used in the “app.js” file to handle form data. Then pass two inputs with different names, these names are used to get the specific data entered on these inputs, and then finally a button of submit type to submit the form.

Index Html File

Inside the “app.js” file, import the express module.

const express = require('express');

Create a constant “app” and set it to “express()”, which means creating an instance of an express module, by which any of the express functions can be called.

const app = express();

Then initialize the express to parse JSON data to get the form data, the form data is nested data so we also have to specify the URL encoding as extended true.

app.use(express.json());       
app.use(express.urlencoded({extended: true})); 

Then use the express get method to define the logic for the “/” route. Inside this method, use res.sendFile() method which is used to send the HTML file we just created as a response.

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html");
});

Use the post method of express to handle the post request, we have already set the method to post in the HTML file, and then we specify the route for which we want to handle the post request and the route is “/” which we also define as an HTML file.

app.post("/", (req, res) => {
  
});

Inside this method, we fetch the username and password with the name specified to the input using the res which is a response object. Then pass the value into individual constant and log the constant in the console using the console global object. Then finally end the method by sending a message as a response.

app.post("/", (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  console.log("Username: " + username);
  console.log("Password: " + password);
  res.send("Data received");
});

Create a port to test our application on browsers, using listen() method, and pass the 3000 port as an argument.

app.listen(3000);

Now, inside the browser search bar and type the below URL

http://localhost:3000/

this will open the Node.js application we set to port 3000.

Application In The Browser

Complete Code:

const express = require('express');

const app = express();

app.use(express.json());       
app.use(express.urlencoded({extended: true})); 

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html");
});

app.post("/", (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  console.log("Username: " + username);
  console.log("Password: " + password);
  res.send("Data received");
});

app.listen(3000);

Output:

Output In The Terminal
Output in Terminal
Output In The Browser
Output in Browser

Summary 

Fetching data from the form is useful when creating the application required to get data from users for different purposes like creating a new account, authenticating the user’s username and password, creating the todo, fetching email to send newsletter or authentication code, etc. We hope this tutorial teaches you the method to get the form data in Node.js.

Reference

https://expressjs.com/en/api.html