Categories: Express JSHow to

Create & Process Form with Login example in Express JS

To perform CRUD functions on any website, forms are used. These are most important and widely used as an integral part a website. Forms are used to add, update, remove and delete data. For example, when a user tries to login to any website, he provides his username and password and hit the login key to proceed. The interface containing the fields or input boxes for username and password along with submit button to proceed login makes a form. In order to proceed towards learning forms in Express JS, we will setup body-parser and multer packages. Multer is used to parse multipart form and body-parser is used to parse url-encoded data and JSON. These are middleware and it is necessary to parse any form with them to send data from frontend to backend. Multipart forms are used when we have to upload files via forms.

To start using forms, we will have to install multer and body-parser by executing command below.

# npm install --save body-parser multer

We are using –save so that our package.json file gets updated and when we migrate project, we can generate npm packages by just executing npm install on terminal.

Login Form

We will create a basic login form to learn how to create a form in ExpressJS and Pug templating engine. Create a new file named login.pug in views directory and paste the following code.

doctype html
html
    head
        title Login Form
    body
        form(method="POST", action="/submit")
            label(for = "username") Username:
            input(type = "text", name = "username")
            br
            label(for = "password") Password:
            input(type = "password", name = "password")
            br
            input(type = "submit", name = "submit", value = "submit")

The above code will create a login form with username and password fields along with a submit button to proceed login as shown below.

From the above code, you can see we have created a form to send POST request. Therefore, we will make a new route in our index.js file to handle this POST request as shown in the given code. Copy and replace your index.js code with the code below.

//imports express module
let express = require('express');
//initializes express app
let app = express();
//import multer
let multer = require('multer');
//import bodyparser
let bodyParser = require('body-parser');
//sets template engine
app.set('view engine', 'pug');
//sets directory name
app.set('views','./views');
//use middleware to serve static files
app.use('/static', express.static('public'));
//to parse multipart form that is multipart/form-data
app.use(multer().array());
//to parse urlencoded form that is application/xwww-
app.use(bodyParser.urlencoded({extended: true}));
//to parse json data that is application/json
app.use(bodyParser.json());

app.get('/', function(request, response){
    //render hello Pug template with user object
    console.log(request.body);
    response.render('login');
});
//receive post request from form
app.post('/submit', function(request, response){
    //render hello Pug template with user object
    console.log(request.body);
    response.send("Data for " + request.body.username + " submitted successfully!");
});
//listens to server at port 3000
app.listen(3000);

To check our code, we have written username value as “Learn Cybers” and any value for password. After submission, we have received the following output on screen indicating that Data for Learn Cybers submitted successfully.

We have received form data from frontend by parsing the form using body and attaching field name after this keyword. Now you can see, we are receiving data from user via forms and showing the values entered by user on frontend via views. But we have not stored any value yet. Whenever, the user refreshes webpage, the data gets lost. Here is the point where databases come in.

Arslan ud Din Shafiq

Alibaba Cloud MVP, Alibaba Cloud Technical Author, Dzone MVB, Software Engineer, Software Developer, Software Designer, Web Engineer, Web Developer, Web Designer, Database Designer, Database Developer, Cloud Computing Specialist, Linux Expert, Servers, 3D Modeling, Blogger, Facebook Map Editor, Google Map Editor

Recent Posts

How To Set Up Secure Nginx Server Blocks on Ubuntu 22.04

NGINX Server Nginx, a popular open-source web server, excels at handling high traffic websites efficiently.… Read More

9 hours ago

The Web Server Showdown: Nginx vs. Apache, LiteSpeed, Caddy, and Beyond

In the realm of web hosting, choosing the right web server is paramount. It acts… Read More

9 hours ago

Linear guidance systems

Are indispensable for ensuring smooth, precise linear motion in many industrial applications. Whether in robotics,… Read More

2 months ago

Cyber Attack Statistics – Identifying Vulnerabilities and Strengthening Defenses

Cyber attacks are becoming more frequent, complex, and damaging. They can disrupt critical operations and… Read More

3 months ago

Empowering Cybersecurity in 2024 with XDR for Comprehensive Threat Detection and Response

With the rise of new threats and the increasing complexity of IT environments, organizations need… Read More

3 months ago

Facade Design Pattern: Simplifying Complex Systems

1. Introduction In software design, managing complex systems can be challenging. The Facade Design Pattern… Read More

4 months ago