Express Routers, Middleware, Databases, Credit Cards




CS174

Chris Pollett

May 8, 2017

Outline

Patterns and variables in Express Routes

var express = require('express');
var app = express();
app.get('/', function (req, res) {
    res.send('The Love Web App');
});
// routes can match a string express involving *, ? (, )
app.get('/*love*', function (req, res) {
    res.send('There are many routes to love.<br />' +
        'Yours was ' + req.path);
});
// You can also use regular expressions
app.get(/l(u|a)+v(e)?$/, function (req, res) {
    res.send('Your route ends with ' + req.path + "<br />"+
        'Your regex capture groups were [0]=>' +   req.params[0] +
        " [1] =>"+ req.params[1]);
    console.log(req);
});
// this example shows getting req parameter from a pattern
app.get('/luv/:from-:to', function (req, res) {
    var from =  (typeof req.params.from !== 'undefined')
        ? req.params.from : "Everyone";
    var to =  (typeof req.params.to !== 'undefined') ?
        req.params.to : "someone";
    res.send(from + ' sends their love to ' + to);
});
// You can specify a sequence of handlers each as separate arguments
app.get('/lost', function (req, res, next) {
        console.log(req.ip + " seems lost in love!");
        next()
    }, function (req, res) {
       console.log("Redirecting love to a more fruitful place...");
       res.redirect(301,'/love'); 
    }
);
// Or you can specify an array of functions
var lust1 = function (req, res, next) {
    console.log(req.ip + " has confused lust for /love");
    next(); // call the next handler
}
var lust2 = function (req, res) {
       console.log("Redirecting lust to love");
       res.redirect(301,'/love'); 
    }
app.get('/lust', [lust1, lust2]);
//You can combine requests to the same url path but different methods as
app.route('/form').get(function(req,res) {
    res.send('<form method="post"><button>Submit</button></form>');
}).post(function(req, res) {
    res.send('You submitted the love form');
});
//start app listening
app.listen(8888, function () {
    console.log('Server up!')
});

More on Router Modules

More on Modules

Express Middleware

Node Database Integration

Node Database Integration - continued

Remarks on Database Code

Prepared Statements

var mysql = require('mysql')
// set-up and connect
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'root',
  database : 'FOO'
});
if (typeof process.argv[2] === 'undefined') {
    console.log('This command should be run with a line like:\n' +
        'node prepare_db.js some_number');
    process.exit();
}

connection.connect();
/* For strings we can use ?? if we want the formatter to escape them
   If we have a variable and we want it interpolated with the same type,
   without escaping, we use ?.
 */
var first_out = parseInt(process.argv[2])
var sql = mysql.format('SELECT ?? FROM TEST LIMIT ?',
    ["ID", first_out]);
connection.query(sql,
    function (error, results, fields) {
        if (error) throw error;
        console.log(results); // the complete result set
    }
);
/*
  Like many node object, a query also generates events when
  things happen, such as a single row in the results has been received.
  We can handle these using the "on" method.
  Notice below we also skip the mysql.format step
 */
var query = connection.query('SELECT ID FROM TEST LIMIT ?', [first_out]);
query.on('result', function(row) {
    // Pause so can do I/O without more events
    connection.pause();
    for (var elt in row) {
        console.log( elt + ":" + row[elt]);
    }
    connection.resume();
}).on('end', function() {
    connection.end();
});

setTimeout, setInterval, setImmediate

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Default landing page')
})
// set up rest of app routes

app.listen(8888, function () {
  console.log('Server up!')
});

// background task that gets 
setInterval(function() {
    console.log("Hi there, I'm the cool background task!\n");
}, 5000);
  • There is also a setImmediate function in Node, which queues the callback for immediate execution (i.e., like setTimeout with 0 delay).
  • Sending Email

  • It is often useful to collect a person's e-mail address with a form.
  • By mailing, a person a special code that allows them to complete a registration process, one can verify that one has a real e-mail address of a real person.
  • In PHP, the simplest way to do this is to use the mail() command:
    $message = "Here is a mail message";
    mail("Someone@somewhere.com",
         "Here is the title", 
         $message, 
         "From: cpollett@somewhereelse.com");
    
  • In Node.js, we can do this by installing the nodemailer module:
    npm install nodemailer --save
    
    the following is short node program that demonstrates its use:
    var nodemailer = require('nodemailer');
    
    /* using transport for general smtp server
       nodemailer also has ones for common servers like gmail
    */
    var transporter = nodemailer.createTransport({
        host: 'pollett.org',
        port: 587,
        secure: false, // whether to use TLS
        auth: {
            user: 'cpollett',
            pass: 'somepassword'
        }
    });
    
    var options = {
        from: 'chris@pollett.org', // sender address
        to: 'chris.pollett@sjsu.edu, cpollett@yahoo.com', // list of receivers
        subject: 'Hey Other Chris', // Subject line
        text: 'This is an email from yourself', // plain text body
        html: 'This is an email from yourself' // html body
    };
    
    transporter.sendMail(options, function(error, info) {
        if (error) {
            return console.log(error);
        }
        console.log('Message Sent. Id: %s Res: %s', info.messageId, info.response);
    });
    
  • Quiz

    Which of the following statements is true?

    1. A scalable website was defined to mean a website that could handle increased usage and increased data while remaining maintainable.
    2. C10k is l33t-speak for a kind of clock used in high end reverse proxy servers.
    3. Express is a template HTML module for Node.

    Credit Card Transactions

    Stripe

    Stripe Example - Project Structure

    app.js
    config.js
    node_modules 
        | stuff installed via npm
    package.json
    views
        | index.ejs
        | message.ejs
    

    Stripe Example -- Intuition