Implementing Routes

As part of the Express server configuration, the ./routes.js file shown in Listing 26.3 is loaded. This file implements the routes necessary to support signup, login, editing, and user deletion. This code also implements static routes that support loading the static files.

Notice that req.session is used frequently throughout the routes code. This is the session created when expressSession() middleware was added in the previous section. Notice that the following code is called to clean up the existing session data when the user logs out or is deleted:

req.session.destroy(function(){});

The code attaches text strings to the session.msg variable so that they can be added to the template. (This is just for example purpose so that you can see the status of requests on the webpages.)

Notice at the bottom of Listing 26.3 that the handler function for the routes point to the functions from users_controller, loaded by the following statement:

var users = require('./controllers/users_controller'),

Listing 26.3 provides the full route implementation, including in the application, with the exception of the routes that modify the database; that is discussed in the next section.

Listing 26.3 routes.js: Implementing the Express server routes to handle web requests


01 var crypto = require('crypto'),
02 var express = require('express'),
03 module.exports = function(app) {
04   var users = require('./controllers/users_controller'),
05   app.use('/static', express.static( './static')).
06       use('/lib', express.static( '../lib')
07   );
08   app.get('/', function(req, res){
09     if (req.session.user) {
10       res.render('index', {username: req.session.username,
11                            msg:req.session.msg});
12     } else {
13       req.session.msg = 'Access denied!';
14       res.redirect('/login'),
15     }
16   });
17   app.get('/user', function(req, res){
18     if (req.session.user) {
19       res.render('user', {msg:req.session.msg});
20     } else {
21       req.session.msg = 'Access denied!';
22       res.redirect('/login'),
23     }
24   });
25   app.get('/signup', function(req, res){
26     if(req.session.user){
27       res.redirect('/'),
28     }
29     res.render('signup', {msg:req.session.msg});
30   });
31   app.get('/login',  function(req, res){
32     if(req.session.user){
33       res.redirect('/'),
34     }
35     res.render('login', {msg:req.session.msg});
36   });
37   app.get('/logout', function(req, res){
38     req.session.destroy(function(){
39       res.redirect('/login'),
40     });
41   });
42   app.post('/signup', users.signup);
43   app.post('/user/update', users.updateUser);
44   app.post('/user/delete', users.deleteUser);
45   app.post('/login', users.login);
46   app.get('/user/profile', users.getUserProfile);
47 }


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

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