Process a User Login Form with ExpressJS

This tutorial is part 3 of 7 tutorials that walk through using Express.js for user authentication .

By the end of this tutorial, you will know how to use ExpressJS to create a user login form that validates and sanitizes user input for security.

One way to accept user input into your Node application is by using an HTML <form> element. To use the form data submitted by users we’ll need a Node.js server application to parse it. ExpressJS is a handy framework that simplifies the process of creating server applications. And has helpful extensions to make it easier to handle form submissions.

Goal

Create an HTML login form and use ExpressJS to set up the appropriate routes to navigate through the site and process the input.

Prerequisites

ExpressJS Routing

Hypertext Transfer Protocol (HTTP) is the set of rules used for website communication. The client and the server communicate with a request and response structure. Routing ensures client-side requests receive the proper server response. The 2 types of requests used in this project are GET and POST.

GET Method

The get method fetches data stored on the web server. A request is sent to the server when a user enters a specific URL (say heynode.com). The server will respond with the appropriate web page data.

POST Method

The post method updates or creates data. When a user submits a login form, they send a request back to the server. In return, the server sends a response, such as the user’s dashboard.

Route Path

A route’s path tells the server where data is located.

Handler

When a request is matched to the appropriate route, a function is executed. This function is called a handler. A route handler can contain one or more functions.

Project file structure

Here is how this project is organized:

.
└── login
. ├── package.json
. ├── server.js
. └── static
. . ├── index.html
. . └── login.html

Login form code

We are now ready to create the project.

Create login.html and index.html

Before we get started on our JavaScript code, we will make a simple HTML login form. If you are also responsible for the front-end code, you will probably want to pretty it up with CSS and add validation or other front-end functionality. As is, the form below should be enough to test server-side functionality.

We will save the login form as static/login.html.

<!DOCTYPE html>
<html>
  <head>
	<title>Example Login Form</title>
  </head>
  <body>
	<form action="//members.osiolabs.com/login" method="post">
  	<!-- user input-->
  	Username:<br>
  	<input type="text" name="username" placeholder="Username" required><br><br>
  	Password:<br>
  	<input type="password" name="password" placeholder="Password" required><br><br>
  	<!-- submit button -->
  	<input type="submit" value="login">
	</form>
  </body>
</html>

To demonstrate multiple GET routes, we will also create static/index.html. The index page only contains a link to the login page:

<!DOCTYPE html>
<html>
  <head>
	<title>Welcome Home</title>
  </head>
  <body>
. . <!-- link to login page-->
	<a href="/login">Please Login Here!</a>
  </body>
</html>

Create a package.json file

Assuming you have already installed NodeJS, you are ready to create your package.json file. Create it inside your main project folder (login) by executing the following command:

 npm init -y

Install ExpressJS

While you are still in your main project folder, install ExpressJS and dependencies.

npm install express body-parser

Open server.js

Now, we are ready to work on our server code. Create a server.js and open it in your editor so we can create our project’s server.

Include ExpressJS

The first line in server.js will include the ExpressJS library.

const express = require('express'); // Include ExpressJS

Create an Express application

The second line in server.js will create an ExpressJS application.

const app = express(); // Create an ExpressJS app

Include and use body-parser

When a user fills out our login form, the information gets sent back to the server. The body-parser module is middleware that parses user input and makes it available through the req.body property.

const bodyParser = require('body-parser'); // middleware

And our application is going to use body-parser:

app.use(bodyParser.urlencoded({ extended: false }));
  • .urlencoded indicates that we are parsing URL encoded data from the body. When working with forms, we use the urlencoded parser because by default, forms send data in URL encoded format.
  • extended is an option allowing you to choose which library you want to use to parse the URL encoded data. By default, this option is set to true and will use the qs library. When set to false, like the example above, it uses the QueryString library.

Set up routes for our GET requests

Let’s start with the route to our home page.

// Route to Homepage
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/static/index.html');
});

app.get is a function of:

  • Route Path: ‘/’
  • Route Handler:
    • A function of request (req) and response (res)
    • The server will respond to the get request by sending the file ‘/static/index.html’

Now let’s set up the login route.

// Route to Login Page
app.get('/login', (req, res) => {
  res.sendFile(__dirname + '/static/login.html');
});

app.get is a function of:

  • Route Path: ‘/login’
  • Route Handler:
    • A function of request (req) and response (res)
    • The server will respond to the get request by sending the file ‘/static/login.html’

So far, server.js should look like this:

const express = require('express'); // Include ExpressJS
const app = express(); // Create an ExpressJS app
const bodyParser = require('body-parser'); // Middleware 

app.use(bodyParser.urlencoded({ extended: false }));

// Route to Homepage
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/static/index.html');
});

// Route to Login Page
app.get('/login', (req, res) => {
  res.sendFile(__dirname + '/static/login.html');
});

Set up a route for POST requests

When a user submits the form, we will have to process the request. In a real-life application, the server would probably respond by serving that user their dashboard. In a later tutorial, we will write authentication code and do just that. For this tutorial, we will respond with the user’s username and password.

app.post('/login', (req, res) => {
  // Insert Login Code Here
  let username = req.body.username;
  let password = req.body.password;
  res.send(`Username: ${username} Password: ${password}`);
});

app.post is a function of:

  • Route Path: ‘/login’
  • Route Handler:
    • A function of request (req) and response (res)
    • The username input is stored in a variable called username and the password input is stored in a variable called password. When the form is submitted, we respond by showing the user their username and password.

Assign a port

Lastly, we will assign a port for our application to listen on. ExpressJS’s app.listen function is based on NodeJS’s http.Server.listen function.

const port = 3000 // Port we will listen on

// Function to listen on the port
app.listen(port, () => console.log(`This app is listening on port ${port}`));

Now server.js is complete and should look like this:

const express = require('express'). // Include ExpressJS
const app = express(). // Create an ExpressJS app
const bodyParser = require('body-parser'); // Middleware

app.use(bodyParser.urlencoded({ extended: false }));

// Route to Homepage
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/static/index.html');
});

// Route to Login Page
app.get('/login', (req, res) => {
  res.sendFile(__dirname + '/static/login.html');
});

app.post('/login', (req, res) => {
  // Insert Login Code Here
  let username = req.body.username;
  let password = req.body.password;
  res.send(`Username: ${username} Password: ${password}`);
});

const port = 3000 // Port we will listen on

// Function to listen on the port
app.listen(port, () => console.log(`This app is listening on port ${port}`));

Start the server

Open your local terminal and navigate to the main project folder (login). Run server.js.

node server.js

You should see something like this in the terminal:

candy@tuxie:~/Documents/login$ node server.js
This app is listening on port 3000

Test the code

Finally, we are ready to go to a web browser and test our code. Once in the web browser, navigate to: http://localhost:3000

You should see our home page:

Express server home page with link that says &quot;Please login&quot;

Click on the link “Please Login Here!” and navigate to the login page.

Login form with username and password fields.

Enter a username and password, then submit.

Login form with fields filled in.

After submitting the form, you should see the username and password you entered displayed in the web browser.

Recap

ExpressJS is a NodeJS framework used to create web server software. Web servers route user requests to send back an appropriate response. A get request responds with data stored on the server and is commonly used to navigate a user to the appropriate web page. Post requests update existing data or create new data. They are frequently used to process user input.

ExpressJS routes are functions of a path and handler. The path is where the data is located, and the handler is a function of the client’s request and the server’s response.

Keep going with the next tutorial in this set: How to Validate and Sanitize an ExpressJS Form.

Further your understanding

  • What is the difference between the POST method and PUT method?
  • What are some advantages of creating your own server?
  • What are some disadvantages of creating your own server?

Additional resources