Last active
May 22, 2017 12:11
-
-
Save rttomlinson/fc70a5787b1c430383013f3f7bbdbd28 to your computer and use it in GitHub Desktop.
app.js Express Components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var express = require('express') | |
| var bodyParser = require('body-parser') | |
| var app = express() | |
| // parse application/x-www-form-urlencoded | |
| app.use(bodyParser.urlencoded({ extended: false })) | |
| // parse application/json | |
| app.use(bodyParser.json()) | |
| app.use(function (req, res) { | |
| res.setHeader('Content-Type', 'text/plain') | |
| res.write('you posted:\n') | |
| res.end(JSON.stringify(req.body, null, 2)) | |
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // catch 404 and forward to error handler | |
| app.use(function(req, res, next) { | |
| var err = new Error('Not Found'); | |
| err.status = 404; | |
| next(err); | |
| }); | |
| // error handler | |
| app.use(function(err, req, res, next) { | |
| // set locals, only providing error in development | |
| res.locals.message = err.message; | |
| res.locals.error = req.app.get('env') === 'development' ? err : {}; | |
| // render the error page | |
| res.status(err.status || 500); | |
| res.render('error'); | |
| }); | |
| // ---------------------------------------- | |
| // Error Handling | |
| // ---------------------------------------- | |
| app.use((err, req, res, next) => { | |
| if (res.headersSent) { | |
| return next(err); | |
| } | |
| if (err.stack) { | |
| err = err.stack; | |
| } | |
| res.status(500).render('errors/500', { error: err }); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var expressHandlebars = require('express-handlebars'); | |
| var helpers = require('./helpers'); | |
| // Give registered helpers to Handlebars | |
| var hbs = expressHandlebars.create({ | |
| helpers: helpers.registered, | |
| //... | |
| }); | |
| app.engine('handlebars', hbs.engine); | |
| app.set('view engine', 'handlebars'); | |
| ///////////////////////////////////////////// | |
| var hbs = expressHandlebars.create({ | |
| partialsDir: 'views/', | |
| defaultLayout: 'main' | |
| }); | |
| app.engine('handlebars', hbs.engine); | |
| app.set('view engine', 'handlebars'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Put this AFTER your body-parser set up | |
| app.use((req, res, next) => { | |
| var method; | |
| // Allow method overriding in | |
| // the query string and POST data | |
| // and remove the key after found | |
| if (req.query._method) { | |
| method = req.query._method; | |
| delete req.query._method; | |
| } else if (typeof req.body === 'object' && req.body._method) { | |
| method = req.body._method; | |
| delete req.body._method; | |
| } | |
| // Upcase the method name | |
| // and set the request method | |
| // to override it from GET to | |
| // the desired method | |
| if (method) { | |
| method = method.toUpperCase(); | |
| req.method = method; | |
| } | |
| next(); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ---------------------------------------- | |
| // Logging | |
| // ---------------------------------------- | |
| var morgan = require('morgan'); | |
| app.use(morgan('tiny')); | |
| app.use((req, res, next) => { | |
| ['query', 'params', 'body'].forEach((key) => { | |
| if (req[key]) { | |
| var capKey = key[0].toUpperCase() + key.substr(1); | |
| var value = JSON.stringify(req[key], null, 2); | |
| console.log(`${ capKey }: ${ value }`); | |
| } | |
| }); | |
| next(); | |
| }); | |
| //------------------------------------------------------- | |
| // ---------------------------------------- | |
| // Logging | |
| // ---------------------------------------- | |
| const morgan = require('morgan'); | |
| const highlight = require('cli-highlight').highlight; | |
| // Add :data format token | |
| // to `tiny` format | |
| let format = [ | |
| ':separator', | |
| ':newline', | |
| ':method ', | |
| ':url ', | |
| ':status ', | |
| ':res[content-length] ', | |
| '- :response-time ms', | |
| ':newline', ':newline', | |
| ':data', | |
| ':newline', | |
| ':separator', | |
| ':newline', ':newline', | |
| ].join(''); | |
| // Use morgan middleware with | |
| // custom format | |
| app.use(morgan(format)); | |
| // Helper tokens | |
| morgan.token('separator', () => '****'); | |
| morgan.token('newline', () => "\n"); | |
| // Set data token to output | |
| // req query params and body | |
| morgan.token('data', (req, res, next) => { | |
| let data = []; | |
| ['query', 'params', 'body', 'session'].forEach((key) => { | |
| if (req[key]) { | |
| let capKey = key[0].toUpperCase() + key.substr(1); | |
| let value = JSON.stringify(req[key], null, 2); | |
| data.push(`${ capKey }: ${ value }`); | |
| } | |
| }); | |
| data = highlight(data.join('\n'), { | |
| language: 'json', | |
| ignoreIllegals: true | |
| }); | |
| return `${ data }`; | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ---------------------------------------- | |
| // Referrer | |
| // ---------------------------------------- | |
| app.use((req, res, next) => { | |
| req.session.backUrl = req.header('Referer') || '/'; | |
| next(); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| app.use(express.static(__dirname + "/public")); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var session = require('express-session'); | |
| app.use(session({ | |
| secret: 'keyboard cat', | |
| resave: false, | |
| saveUninitialized: true, | |
| cookie: {} | |
| })); | |
| app.use((req, res, next) => { | |
| res.locals.session = req.session; | |
| res.locals.currentUser = req.session.currentUser; | |
| next(); | |
| }); | |
| // Auth | |
| app.use((req, res, next) => { | |
| var reqUrl = url.parse(req.url); | |
| if (!req.session.currentUser && | |
| !['/', '/login'].includes(reqUrl.pathname)) { | |
| res.redirect('/login'); | |
| } else { | |
| next(); | |
| } | |
| }); | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| router.delete('/cart', function(req, res, next) { | |
| if (req.session) { | |
| req.session.destroy(); | |
| } | |
| req.method = 'GET'; | |
| res.redirect('/products'); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env node | |
| /** | |
| * Module dependencies. | |
| */ | |
| var app = require('../app'); | |
| var debug = require('debug')('express-express-handlebars-boilerplate:server'); | |
| var http = require('http'); | |
| /** | |
| * Get port from environment and store in Express. | |
| */ | |
| var port = normalizePort(process.env.PORT || '3000'); | |
| app.set('port', port); | |
| /** | |
| * Create HTTP server. | |
| */ | |
| var server = http.createServer(app); | |
| /** | |
| * Listen on provided port, on all network interfaces. | |
| */ | |
| server.listen(port); | |
| server.on('error', onError); | |
| server.on('listening', onListening); | |
| /** | |
| * Normalize a port into a number, string, or false. | |
| */ | |
| function normalizePort(val) { | |
| var port = parseInt(val, 10); | |
| if (isNaN(port)) { | |
| // named pipe | |
| return val; | |
| } | |
| if (port >= 0) { | |
| // port number | |
| return port; | |
| } | |
| return false; | |
| } | |
| /** | |
| * Event listener for HTTP server "error" event. | |
| */ | |
| function onError(error) { | |
| if (error.syscall !== 'listen') { | |
| throw error; | |
| } | |
| var bind = typeof port === 'string' | |
| ? 'Pipe ' + port | |
| : 'Port ' + port; | |
| // handle specific listen errors with friendly messages | |
| switch (error.code) { | |
| case 'EACCES': | |
| console.error(bind + ' requires elevated privileges'); | |
| process.exit(1); | |
| break; | |
| case 'EADDRINUSE': | |
| console.error(bind + ' is already in use'); | |
| process.exit(1); | |
| break; | |
| default: | |
| throw error; | |
| } | |
| } | |
| /** | |
| * Event listener for HTTP server "listening" event. | |
| */ | |
| function onListening() { | |
| var addr = server.address(); | |
| var bind = typeof addr === 'string' | |
| ? 'pipe ' + addr | |
| : 'port ' + addr.port; | |
| debug('Listening on ' + bind); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment