CS174
Chris Pollett
May 8, 2017
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!')
});
var express = require('express');
var my_routes1 = express.Router();
my_routes1.get('/a_route', function (req, res) {
res.send('a route for my_routes1');
})
//...define more routes
module.exports = my_routes1;
then use it in our express app.js via:
var my_route = require('./my_routes1');
app.use('/my_path', my_route);
var config = {
prop1: 'value1',
prop2: 'value2',
// ...
}
module.exports = config;
var config = require('./config');
console.log(config.prop1); // or use it in a more interesting way
var express = require('express');
var app = express();
var logger = function (req, res, next) {
req.logger_name = "Super Logger";
console.log((new Date()).toISOString() + ": " + req.method);
next()
}
app.use(logger);
// notice logger gets called before the callbacks below
app.get('/', function (req, res) {
res.send('This is an express app using route ' + req.path +
'<br /> Logger in use ' + req.logger_name);
});
app.listen(8888, function () {
console.log('Server up!')
})
npm install mysql --saveremembering --save adds it to our list of dependencies.
var mysql = require('mysql')
// set-up and connect
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root'
// could also add a database property
});
connection.connect();
// Now issue some commands against the database
connection.query('DROP DATABASE IF EXISTS FOO',
function (error, results, fields) {
if (error) throw error;
// we should do something more interesting for errors
}
);
/*
These query calls are non blocking,
so in theory we should nest them. As is, this
might have a race condition.
*/
connection.query('CREATE DATABASE FOO',
function (error, results, fields) {
if (error) throw error;
}
);
connection.query('USE FOO', function (error, results, fields) {
if (error) throw error;
});
connection.query('CREATE TABLE IF NOT EXISTS TEST(ID INTEGER)',
function (error, results, fields) {
if (error) throw error;
}
);
// Just to illustrate a wqay to escape strings in this module:
var escaped_1 = connection.escape("1");
// Now do an insert
connection.query('INSERT INTO TEST VALUES (' + escaped_1 +
'), (2), (3), (4), (5)',
function (error, results, fields) {
if (error) throw error;
}
);
/* close the connection.
makes sure all queries terminate before closing connection
*/
connection.end(function(err) {
});
console.log("Database Created!");
node create_db.js
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();
});
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);
$message = "Here is a mail message";
mail("Someone@somewhere.com",
"Here is the title",
$message,
"From: cpollett@somewhereelse.com");
npm install nodemailer --savethe 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);
});
Which of the following statements is true?
mkdir credit_app cd credit_app mkdir views npm init npm install express --save npm install body-parser --save npm install path --save npm install request --save npm install ejs --save
app.js
config.js
node_modules
| stuff installed via npm
package.json
views
| index.ejs
| message.ejs