Express POST events

Our Express application currently only renders an index page using the Handlebars template engine. Let's now extend our application to render a login form, and then process the results when a user completes this form, and posts it back to our application.

In order to do this, we will need a login route handler that will accept both HTML GET actions, as well as HTML POST actions. Our application will need to be modified in a few places. Firstly, we will need a handler for a GET request that will use an associated login.hbs view template to render the login form. Secondly, we will need another handler to process the POST request once the user has filled in the form and hit the submit button. This POST handler will need to parse the POST data.

Let's start with the login.hbs view in the views directory, which  contains a simple HTML form, as follows:

<h1>Login</h1> 
<p> 
<form method="post"> 
    <p>{{ErrorMessage}}</p> 
    <p>Username : <input name="username"></input></p> 
    <p>Password : <input name="password"></input></p> 
    <button type="submit">Login</button> 
</form> 
</p> 

Here, we have created an HTML form that contains a few standard form elements. To start with, we have a <p> element to display the view property named {{ErrorMessage}}, which will be used to display any submission errors to the user. Following this, we have two input fields, named username and password, and a button named Login to submit the form.

Now that we have this view in place, we can update our routes/Login.ts file to render this view on a GET request, as follows:

import express from 'express'; 
var router = express.Router(); 
 
router.get('/login', (req: express.Request, res: express.Response) => { 
    res.render('login',  
        {  
            title: 'Express Login' 
        } 
    ); 
}); 
 
export { router } ; 

Here, we have modified our route handler to simply render the 'login' view, and set the title property to a string containing the value 'Express Login'. Running our application now and navigating to http://localhost:3000/login will invoke our login request handler, and display our simple login form as follows:

Now that our login form has been rendered, we can focus on processing the form values when they have been submitted. Clicking on the Login button will cause the HTML page to generate a POST message to the login request handler. We therefore need to specify a handler that will pick up this POST message. In order to do this, we need to modify our Login.ts handler, and included a new POST handler, as follows:

router.post('/login', (req, res, next) => { 
    if (req.body.name.length > 0) { 
        req.session!['username'] = req.body.username; 
        res.redirect('/'); 
    } else { 
        res.render('login', {  
            title: 'Express', 
            ErrorMessage: 'Please enter a user name' 
            }); 
    } 
}); 

Here, we are calling the post method of the router module. As we saw with the get function, Express uses the post function to set up a POST event handler within our module.

This post handler is checking the request.body.username property to read the form data out of the posted form request. If the username property is valid (which in this case is just that it has been entered), we store the value in the session property named req.session['username'], and redirect the browser to the default page. If the username property has not been entered, we simply re-render the login view, and display an error message.

Before we test this new login page, however, we will need to install and configure a few node modules, as follows:

npm install body-parser --save
npm install cookie-parser --save
npm install express-session --save  

The body-parser module is used to parse form data as a result of a POST event, and attach this form data to the request object itself. This means that we can simply use req.body to dereference the form's data.

The cookie-parser and express-session modules are used for session handling. In our login POST handler, we are setting a session variable to the username property of the form data. This will not work without these two modules.

The final change we need to make is to import these modules into our application, and run through any configuration that they need. We will therefore need to update our app.ts application file as follows:

// existing code 
app.set('view engine', 'hbs'); 
 
import bodyParser from 'body-parser'; 
import cookieParser from 'cookie-parser'; 
import expressSession from 'express-session'; 
 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: false })); 
app.use(cookieParser()); 
app.use(expressSession({ secret : 'asdf' })); 
 
// existing code 
app.use('/', Index.router); 

Here, we are importing the new modules using our standard import module syntax. We are then running through four app.use function calls, in order to configure each of our modules. The body-parser module uses the json() function call to return middleware that Express will use to convert incoming requests into objects attached to req.body. The body-parser also needs to set the urlencoded property in order to allow for JSON-like objects to be exposed. These two settings will create a POJO available via the req.body property when receiving POST requests.

The cookie-parser module is configured by simply using the exported constructor function, and the express-session module is also configured in the same way. Note that both the cookie-parser and express-session modules are needed in order to store variables in the req.session object.

With these modules in place, our POST request handler will be able to query req.body.username to find the username that was entered, and req.body.password to find the corresponding password. It will also be able to store values in the session.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.173.227