diff --git a/examples/README.md b/examples/README.md deleted file mode 100644 index c19ed30a25..0000000000 --- a/examples/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# Express examples - -This page contains list of examples using Express. - -- [auth](./auth) - Authentication with login and password -- [content-negotiation](./content-negotiation) - HTTP content negotiation -- [cookie-sessions](./cookie-sessions) - Working with cookie-based sessions -- [cookies](./cookies) - Working with cookies -- [downloads](./downloads) - Transferring files to client -- [ejs](./ejs) - Working with Embedded JavaScript templating (ejs) -- [error-pages](./error-pages) - Creating error pages -- [error](./error) - Working with error middleware -- [hello-world](./hello-world) - Simple request handler -- [markdown](./markdown) - Markdown as template engine -- [multi-router](./multi-router) - Working with multiple Express routers -- [multipart](./multipart) - Accepting multipart-encoded forms -- [mvc](./mvc) - MVC-style controllers -- [online](./online) - Tracking online user activity with `online` and `redis` packages -- [params](./params) - Working with route parameters -- [resource](./resource) - Multiple HTTP operations on the same resource -- [route-map](./route-map) - Organizing routes using a map -- [route-middleware](./route-middleware) - Working with route middleware -- [route-separation](./route-separation) - Organizing routes per each resource -- [search](./search) - Search API -- [session](./session) - User sessions -- [static-files](./static-files) - Serving static files -- [vhost](./vhost) - Working with virtual hosts -- [view-constructor](./view-constructor) - Rendering views dynamically -- [view-locals](./view-locals) - Saving data in request object between middleware calls -- [web-service](./web-service) - Simple API service diff --git a/examples/auth/index.js b/examples/auth/index.js deleted file mode 100644 index 36205d0f99..0000000000 --- a/examples/auth/index.js +++ /dev/null @@ -1,133 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../..'); -var hash = require('pbkdf2-password')() -var path = require('path'); -var session = require('express-session'); - -var app = module.exports = express(); - -// config - -app.set('view engine', 'ejs'); -app.set('views', path.join(__dirname, 'views')); - -// middleware - -app.use(express.urlencoded({ extended: false })) -app.use(session({ - resave: false, // don't save session if unmodified - saveUninitialized: false, // don't create session until something stored - secret: 'shhhh, very secret' -})); - -// Session-persisted message middleware - -app.use(function(req, res, next){ - var err = req.session.error; - var msg = req.session.success; - delete req.session.error; - delete req.session.success; - res.locals.message = ''; - if (err) res.locals.message = '

' + err + '

'; - if (msg) res.locals.message = '

' + msg + '

'; - next(); -}); - -// dummy database - -var users = { - tj: { name: 'tj' } -}; - -// when you create a user, generate a salt -// and hash the password ('foobar' is the pass here) - -hash({ password: 'foobar' }, function (err, pass, salt, hash) { - if (err) throw err; - // store the salt & hash in the "db" - users.tj.salt = salt; - users.tj.hash = hash; -}); - - -// Authenticate using our plain-object database of doom! - -function authenticate(name, pass, fn) { - if (!module.parent) console.log('authenticating %s:%s', name, pass); - var user = users[name]; - // query the db for the given username - if (!user) return fn(null, null) - // apply the same algorithm to the POSTed password, applying - // the hash against the pass / salt, if there is a match we - // found the user - hash({ password: pass, salt: user.salt }, function (err, pass, salt, hash) { - if (err) return fn(err); - if (hash === user.hash) return fn(null, user) - fn(null, null) - }); -} - -function restrict(req, res, next) { - if (req.session.user) { - next(); - } else { - req.session.error = 'Access denied!'; - res.redirect('/login'); - } -} - -app.get('/', function(req, res){ - res.redirect('/login'); -}); - -app.get('/restricted', restrict, function(req, res){ - res.send('Wahoo! restricted area, click to logout'); -}); - -app.get('/logout', function(req, res){ - // destroy the user's session to log them out - // will be re-created next request - req.session.destroy(function(){ - res.redirect('/'); - }); -}); - -app.get('/login', function(req, res){ - res.render('login'); -}); - -app.post('/login', function (req, res, next) { - authenticate(req.body.username, req.body.password, function(err, user){ - if (err) return next(err) - if (user) { - // Regenerate session when signing in - // to prevent fixation - req.session.regenerate(function(){ - // Store the user's primary key - // in the session store to be retrieved, - // or in this case the entire user object - req.session.user = user; - req.session.success = 'Authenticated as ' + user.name - + ' click to logout. ' - + ' You may now access /restricted.'; - res.redirect('back'); - }); - } else { - req.session.error = 'Authentication failed, please check your ' - + ' username and password.' - + ' (use "tj" and "foobar")'; - res.redirect('/login'); - } - }); -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/auth/views/foot.ejs b/examples/auth/views/foot.ejs deleted file mode 100644 index b605728ee2..0000000000 --- a/examples/auth/views/foot.ejs +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/examples/auth/views/head.ejs b/examples/auth/views/head.ejs deleted file mode 100644 index 65386267d0..0000000000 --- a/examples/auth/views/head.ejs +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - <%= title %> - - - diff --git a/examples/auth/views/login.ejs b/examples/auth/views/login.ejs deleted file mode 100644 index 181c36caf7..0000000000 --- a/examples/auth/views/login.ejs +++ /dev/null @@ -1,21 +0,0 @@ - -<%- include('head', { title: 'Authentication Example' }) -%> - -

Login

-<%- message %> -Try accessing /restricted, then authenticate with "tj" and "foobar". -
-

- - -

-

- - -

-

- -

-
- -<%- include('foot') -%> diff --git a/examples/content-negotiation/db.js b/examples/content-negotiation/db.js deleted file mode 100644 index f59b23bf18..0000000000 --- a/examples/content-negotiation/db.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict' - -var users = []; - -users.push({ name: 'Tobi' }); -users.push({ name: 'Loki' }); -users.push({ name: 'Jane' }); - -module.exports = users; diff --git a/examples/content-negotiation/index.js b/examples/content-negotiation/index.js deleted file mode 100644 index 280a4e2299..0000000000 --- a/examples/content-negotiation/index.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict' - -var express = require('../../'); -var app = module.exports = express(); -var users = require('./db'); - -// so either you can deal with different types of formatting -// for expected response in index.js -app.get('/', function(req, res){ - res.format({ - html: function(){ - res.send(''); - }, - - text: function(){ - res.send(users.map(function(user){ - return ' - ' + user.name + '\n'; - }).join('')); - }, - - json: function(){ - res.json(users); - } - }); -}); - -// or you could write a tiny middleware like -// this to add a layer of abstraction -// and make things a bit more declarative: - -function format(path) { - var obj = require(path); - return function(req, res){ - res.format(obj); - }; -} - -app.get('/users', format('./users')); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/content-negotiation/users.js b/examples/content-negotiation/users.js deleted file mode 100644 index fe703e73a9..0000000000 --- a/examples/content-negotiation/users.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict' - -var users = require('./db'); - -exports.html = function(req, res){ - res.send(''); -}; - -exports.text = function(req, res){ - res.send(users.map(function(user){ - return ' - ' + user.name + '\n'; - }).join('')); -}; - -exports.json = function(req, res){ - res.json(users); -}; diff --git a/examples/cookie-sessions/index.js b/examples/cookie-sessions/index.js deleted file mode 100644 index 01c731c1c8..0000000000 --- a/examples/cookie-sessions/index.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var cookieSession = require('cookie-session'); -var express = require('../../'); - -var app = module.exports = express(); - -// add req.session cookie support -app.use(cookieSession({ secret: 'manny is cool' })); - -// do something with the session -app.use(count); - -// custom middleware -function count(req, res) { - req.session.count = (req.session.count || 0) + 1 - res.send('viewed ' + req.session.count + ' times\n') -} - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/cookies/index.js b/examples/cookies/index.js deleted file mode 100644 index 04093591f7..0000000000 --- a/examples/cookies/index.js +++ /dev/null @@ -1,49 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../../'); -var app = module.exports = express(); -var logger = require('morgan'); -var cookieParser = require('cookie-parser'); - -// custom log format -if (process.env.NODE_ENV !== 'test') app.use(logger(':method :url')) - -// parses request cookies, populating -// req.cookies and req.signedCookies -// when the secret is passed, used -// for signing the cookies. -app.use(cookieParser('my secret here')); - -// parses x-www-form-urlencoded -app.use(express.urlencoded({ extended: false })) - -app.get('/', function(req, res){ - if (req.cookies.remember) { - res.send('Remembered :). Click to forget!.'); - } else { - res.send('

Check to ' - + '.

'); - } -}); - -app.get('/forget', function(req, res){ - res.clearCookie('remember'); - res.redirect('back'); -}); - -app.post('/', function(req, res){ - var minute = 60000; - if (req.body.remember) res.cookie('remember', 1, { maxAge: minute }); - res.redirect('back'); -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git "a/examples/downloads/files/CCTV\345\244\247\350\265\233\344\270\212\346\265\267\345\210\206\350\265\233\345\214\272.txt" "b/examples/downloads/files/CCTV\345\244\247\350\265\233\344\270\212\346\265\267\345\210\206\350\265\233\345\214\272.txt" deleted file mode 100644 index 3b049c3168..0000000000 --- "a/examples/downloads/files/CCTV\345\244\247\350\265\233\344\270\212\346\265\267\345\210\206\350\265\233\345\214\272.txt" +++ /dev/null @@ -1,2 +0,0 @@ -Only for test. -The file name is faked. \ No newline at end of file diff --git a/examples/downloads/files/amazing.txt b/examples/downloads/files/amazing.txt deleted file mode 100644 index c478ec5691..0000000000 --- a/examples/downloads/files/amazing.txt +++ /dev/null @@ -1 +0,0 @@ -what an amazing download \ No newline at end of file diff --git a/examples/downloads/files/notes/groceries.txt b/examples/downloads/files/notes/groceries.txt deleted file mode 100644 index fb43877709..0000000000 --- a/examples/downloads/files/notes/groceries.txt +++ /dev/null @@ -1,3 +0,0 @@ -* milk -* eggs -* bread diff --git a/examples/downloads/index.js b/examples/downloads/index.js deleted file mode 100644 index 6b67e0c886..0000000000 --- a/examples/downloads/index.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../../'); -var path = require('path'); - -var app = module.exports = express(); - -// path to where the files are stored on disk -var FILES_DIR = path.join(__dirname, 'files') - -app.get('/', function(req, res){ - res.send('') -}); - -// /files/* is accessed via req.params[0] -// but here we name it :file -app.get('/files/:file(*)', function(req, res, next){ - res.download(req.params.file, { root: FILES_DIR }, function (err) { - if (!err) return; // file sent - if (err.status !== 404) return next(err); // non-404 error - // file for download not found - res.statusCode = 404; - res.send('Cant find that file, sorry!'); - }); -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/ejs/index.js b/examples/ejs/index.js deleted file mode 100644 index a39d805a16..0000000000 --- a/examples/ejs/index.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../../'); -var path = require('path'); - -var app = module.exports = express(); - -// Register ejs as .html. If we did -// not call this, we would need to -// name our views foo.ejs instead -// of foo.html. The __express method -// is simply a function that engines -// use to hook into the Express view -// system by default, so if we want -// to change "foo.ejs" to "foo.html" -// we simply pass _any_ function, in this -// case `ejs.__express`. - -app.engine('.html', require('ejs').__express); - -// Optional since express defaults to CWD/views - -app.set('views', path.join(__dirname, 'views')); - -// Path to our public directory - -app.use(express.static(path.join(__dirname, 'public'))); - -// Without this you would need to -// supply the extension to res.render() -// ex: res.render('users.html'). -app.set('view engine', 'html'); - -// Dummy users -var users = [ - { name: 'tobi', email: 'tobi@learnboost.com' }, - { name: 'loki', email: 'loki@learnboost.com' }, - { name: 'jane', email: 'jane@learnboost.com' } -]; - -app.get('/', function(req, res){ - res.render('users', { - users: users, - title: "EJS example", - header: "Some users" - }); -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/ejs/public/stylesheets/style.css b/examples/ejs/public/stylesheets/style.css deleted file mode 100644 index db60b89fe6..0000000000 --- a/examples/ejs/public/stylesheets/style.css +++ /dev/null @@ -1,4 +0,0 @@ -body { - padding: 50px 80px; - font: 14px "Helvetica Neue", "Lucida Grande", Arial, sans-serif; -} diff --git a/examples/ejs/views/footer.html b/examples/ejs/views/footer.html deleted file mode 100644 index 308b1d01b6..0000000000 --- a/examples/ejs/views/footer.html +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/examples/ejs/views/header.html b/examples/ejs/views/header.html deleted file mode 100644 index c642a15f63..0000000000 --- a/examples/ejs/views/header.html +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - <%= title %> - - - diff --git a/examples/ejs/views/users.html b/examples/ejs/views/users.html deleted file mode 100644 index dad24625e6..0000000000 --- a/examples/ejs/views/users.html +++ /dev/null @@ -1,10 +0,0 @@ -<%- include('header.html') -%> - -

Users

- - -<%- include('footer.html') -%> diff --git a/examples/error-pages/index.js b/examples/error-pages/index.js deleted file mode 100644 index efa815c474..0000000000 --- a/examples/error-pages/index.js +++ /dev/null @@ -1,103 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../../'); -var path = require('path'); -var app = module.exports = express(); -var logger = require('morgan'); -var silent = process.env.NODE_ENV === 'test' - -// general config -app.set('views', path.join(__dirname, 'views')); -app.set('view engine', 'ejs'); - -// our custom "verbose errors" setting -// which we can use in the templates -// via settings['verbose errors'] -app.enable('verbose errors'); - -// disable them in production -// use $ NODE_ENV=production node examples/error-pages -if (app.settings.env === 'production') app.disable('verbose errors') - -silent || app.use(logger('dev')); - -// Routes - -app.get('/', function(req, res){ - res.render('index.ejs'); -}); - -app.get('/404', function(req, res, next){ - // trigger a 404 since no other middleware - // will match /404 after this one, and we're not - // responding here - next(); -}); - -app.get('/403', function(req, res, next){ - // trigger a 403 error - var err = new Error('not allowed!'); - err.status = 403; - next(err); -}); - -app.get('/500', function(req, res, next){ - // trigger a generic (500) error - next(new Error('keyboard cat!')); -}); - -// Error handlers - -// Since this is the last non-error-handling -// middleware use()d, we assume 404, as nothing else -// responded. - -// $ curl http://localhost:3000/notfound -// $ curl http://localhost:3000/notfound -H "Accept: application/json" -// $ curl http://localhost:3000/notfound -H "Accept: text/plain" - -app.use(function(req, res, next){ - res.status(404); - - res.format({ - html: function () { - res.render('404', { url: req.url }) - }, - json: function () { - res.json({ error: 'Not found' }) - }, - default: function () { - res.type('txt').send('Not found') - } - }) -}); - -// error-handling middleware, take the same form -// as regular middleware, however they require an -// arity of 4, aka the signature (err, req, res, next). -// when connect has an error, it will invoke ONLY error-handling -// middleware. - -// If we were to next() here any remaining non-error-handling -// middleware would then be executed, or if we next(err) to -// continue passing the error, only error-handling middleware -// would remain being executed, however here -// we simply respond with an error page. - -app.use(function(err, req, res, next){ - // we may use properties of the error object - // here and next(err) appropriately, or if - // we possibly recovered from the error, simply next(). - res.status(err.status || 500); - res.render('500', { error: err }); -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/error-pages/views/404.ejs b/examples/error-pages/views/404.ejs deleted file mode 100644 index d992ce0229..0000000000 --- a/examples/error-pages/views/404.ejs +++ /dev/null @@ -1,3 +0,0 @@ -<%- include('error_header') -%> -

Cannot find <%= url %>

-<%- include('footer') -%> diff --git a/examples/error-pages/views/500.ejs b/examples/error-pages/views/500.ejs deleted file mode 100644 index c9d855f804..0000000000 --- a/examples/error-pages/views/500.ejs +++ /dev/null @@ -1,8 +0,0 @@ -<%- include('error_header') -%> -

Error: <%= error.message %>

-<% if (settings['verbose errors']) { %> -
<%= error.stack %>
-<% } else { %> -

An error occurred!

-<% } %> -<%- include('footer') -%> diff --git a/examples/error-pages/views/error_header.ejs b/examples/error-pages/views/error_header.ejs deleted file mode 100644 index b2451ab324..0000000000 --- a/examples/error-pages/views/error_header.ejs +++ /dev/null @@ -1,10 +0,0 @@ - - - - - -Error - - - -

An error occurred!

diff --git a/examples/error-pages/views/footer.ejs b/examples/error-pages/views/footer.ejs deleted file mode 100644 index 308b1d01b6..0000000000 --- a/examples/error-pages/views/footer.ejs +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/examples/error-pages/views/index.ejs b/examples/error-pages/views/index.ejs deleted file mode 100644 index ae8c92820a..0000000000 --- a/examples/error-pages/views/index.ejs +++ /dev/null @@ -1,20 +0,0 @@ - - - - - -Custom Pages Example - - - -

My Site

-

Pages Example

- - - - - diff --git a/examples/error/index.js b/examples/error/index.js deleted file mode 100644 index d733a81172..0000000000 --- a/examples/error/index.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../../'); -var logger = require('morgan'); -var app = module.exports = express(); -var test = app.get('env') === 'test' - -if (!test) app.use(logger('dev')); - -// error handling middleware have an arity of 4 -// instead of the typical (req, res, next), -// otherwise they behave exactly like regular -// middleware, you may have several of them, -// in different orders etc. - -function error(err, req, res, next) { - // log it - if (!test) console.error(err.stack); - - // respond with 500 "Internal Server Error". - res.status(500); - res.send('Internal Server Error'); -} - -app.get('/', function () { - // Caught and passed down to the errorHandler middleware - throw new Error('something broke!'); -}); - -app.get('/next', function(req, res, next){ - // We can also pass exceptions to next() - // The reason for process.nextTick() is to show that - // next() can be called inside an async operation, - // in real life it can be a DB read or HTTP request. - process.nextTick(function(){ - next(new Error('oh no!')); - }); -}); - -// the error handler is placed after routes -// if it were above it would not receive errors -// from app.get() etc -app.use(error); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/hello-world/index.js b/examples/hello-world/index.js deleted file mode 100644 index 8c1855c2eb..0000000000 --- a/examples/hello-world/index.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict' - -var express = require('../../'); - -var app = module.exports = express() - -app.get('/', function(req, res){ - res.send('Hello World'); -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/markdown/index.js b/examples/markdown/index.js deleted file mode 100644 index 23d645e66b..0000000000 --- a/examples/markdown/index.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var escapeHtml = require('escape-html'); -var express = require('../..'); -var fs = require('fs'); -var marked = require('marked'); -var path = require('path'); - -var app = module.exports = express(); - -// register .md as an engine in express view system - -app.engine('md', function(path, options, fn){ - fs.readFile(path, 'utf8', function(err, str){ - if (err) return fn(err); - var html = marked.parse(str).replace(/\{([^}]+)\}/g, function(_, name){ - return escapeHtml(options[name] || ''); - }); - fn(null, html); - }); -}); - -app.set('views', path.join(__dirname, 'views')); - -// make it the default, so we don't need .md -app.set('view engine', 'md'); - -app.get('/', function(req, res){ - res.render('index', { title: 'Markdown Example' }); -}); - -app.get('/fail', function(req, res){ - res.render('missing', { title: 'Markdown Example' }); -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/markdown/views/index.md b/examples/markdown/views/index.md deleted file mode 100644 index b0b2e7176f..0000000000 --- a/examples/markdown/views/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# {title} - -Just an example view rendered with _markdown_. \ No newline at end of file diff --git a/examples/multi-router/controllers/api_v1.js b/examples/multi-router/controllers/api_v1.js deleted file mode 100644 index a301e3ee72..0000000000 --- a/examples/multi-router/controllers/api_v1.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict' - -var express = require('../../..'); - -var apiv1 = express.Router(); - -apiv1.get('/', function(req, res) { - res.send('Hello from APIv1 root route.'); -}); - -apiv1.get('/users', function(req, res) { - res.send('List of APIv1 users.'); -}); - -module.exports = apiv1; diff --git a/examples/multi-router/controllers/api_v2.js b/examples/multi-router/controllers/api_v2.js deleted file mode 100644 index e997fb1f88..0000000000 --- a/examples/multi-router/controllers/api_v2.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict' - -var express = require('../../..'); - -var apiv2 = express.Router(); - -apiv2.get('/', function(req, res) { - res.send('Hello from APIv2 root route.'); -}); - -apiv2.get('/users', function(req, res) { - res.send('List of APIv2 users.'); -}); - -module.exports = apiv2; diff --git a/examples/multi-router/index.js b/examples/multi-router/index.js deleted file mode 100644 index dbfd284126..0000000000 --- a/examples/multi-router/index.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict' - -var express = require('../..'); - -var app = module.exports = express(); - -app.use('/api/v1', require('./controllers/api_v1')); -app.use('/api/v2', require('./controllers/api_v2')); - -app.get('/', function(req, res) { - res.send('Hello from root route.') -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/multipart/index.js b/examples/multipart/index.js deleted file mode 100644 index ea7b86e0c9..0000000000 --- a/examples/multipart/index.js +++ /dev/null @@ -1,62 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../..'); -var multiparty = require('multiparty'); -var format = require('util').format; - -var app = module.exports = express(); - -app.get('/', function(req, res){ - res.send('
' - + '

Title:

' - + '

Image:

' - + '

' - + '
'); -}); - -app.post('/', function(req, res, next){ - // create a form to begin parsing - var form = new multiparty.Form(); - var image; - var title; - - form.on('error', next); - form.on('close', function(){ - res.send(format('\nuploaded %s (%d Kb) as %s' - , image.filename - , image.size / 1024 | 0 - , title)); - }); - - // listen on field event for title - form.on('field', function(name, val){ - if (name !== 'title') return; - title = val; - }); - - // listen on part event for image file - form.on('part', function(part){ - if (!part.filename) return; - if (part.name !== 'image') return part.resume(); - image = {}; - image.filename = part.filename; - image.size = 0; - part.on('data', function(buf){ - image.size += buf.length; - }); - }); - - - // parse the form - form.parse(req); -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(4000); - console.log('Express started on port 4000'); -} diff --git a/examples/mvc/controllers/main/index.js b/examples/mvc/controllers/main/index.js deleted file mode 100644 index 74cde191cd..0000000000 --- a/examples/mvc/controllers/main/index.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict' - -exports.index = function(req, res){ - res.redirect('/users'); -}; diff --git a/examples/mvc/controllers/pet/index.js b/examples/mvc/controllers/pet/index.js deleted file mode 100644 index 214160f9a4..0000000000 --- a/examples/mvc/controllers/pet/index.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var db = require('../../db'); - -exports.engine = 'ejs'; - -exports.before = function(req, res, next){ - var pet = db.pets[req.params.pet_id]; - if (!pet) return next('route'); - req.pet = pet; - next(); -}; - -exports.show = function(req, res, next){ - res.render('show', { pet: req.pet }); -}; - -exports.edit = function(req, res, next){ - res.render('edit', { pet: req.pet }); -}; - -exports.update = function(req, res, next){ - var body = req.body; - req.pet.name = body.pet.name; - res.message('Information updated!'); - res.redirect('/pet/' + req.pet.id); -}; diff --git a/examples/mvc/controllers/pet/views/edit.ejs b/examples/mvc/controllers/pet/views/edit.ejs deleted file mode 100644 index 655666e010..0000000000 --- a/examples/mvc/controllers/pet/views/edit.ejs +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - -Edit <%= pet.name %> - - - -

<%= pet.name %>

-
- - -
- - diff --git a/examples/mvc/controllers/pet/views/show.ejs b/examples/mvc/controllers/pet/views/show.ejs deleted file mode 100644 index 7e1e338e7d..0000000000 --- a/examples/mvc/controllers/pet/views/show.ejs +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - -<%= pet.name %> - - - -

<%= pet.name %> edit

- -

You are viewing <%= pet.name %>

- - diff --git a/examples/mvc/controllers/user-pet/index.js b/examples/mvc/controllers/user-pet/index.js deleted file mode 100644 index 42a29adebe..0000000000 --- a/examples/mvc/controllers/user-pet/index.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var db = require('../../db'); - -exports.name = 'pet'; -exports.prefix = '/user/:user_id'; - -exports.create = function(req, res, next){ - var id = req.params.user_id; - var user = db.users[id]; - var body = req.body; - if (!user) return next('route'); - var pet = { name: body.pet.name }; - pet.id = db.pets.push(pet) - 1; - user.pets.push(pet); - res.message('Added pet ' + body.pet.name); - res.redirect('/user/' + id); -}; diff --git a/examples/mvc/controllers/user/index.js b/examples/mvc/controllers/user/index.js deleted file mode 100644 index ec3ae4c811..0000000000 --- a/examples/mvc/controllers/user/index.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var db = require('../../db'); - -exports.engine = 'hbs'; - -exports.before = function(req, res, next){ - var id = req.params.user_id; - if (!id) return next(); - // pretend to query a database... - process.nextTick(function(){ - req.user = db.users[id]; - // cant find that user - if (!req.user) return next('route'); - // found it, move on to the routes - next(); - }); -}; - -exports.list = function(req, res, next){ - res.render('list', { users: db.users }); -}; - -exports.edit = function(req, res, next){ - res.render('edit', { user: req.user }); -}; - -exports.show = function(req, res, next){ - res.render('show', { user: req.user }); -}; - -exports.update = function(req, res, next){ - var body = req.body; - req.user.name = body.user.name; - res.message('Information updated!'); - res.redirect('/user/' + req.user.id); -}; diff --git a/examples/mvc/controllers/user/views/edit.hbs b/examples/mvc/controllers/user/views/edit.hbs deleted file mode 100644 index 2be7ddc4a9..0000000000 --- a/examples/mvc/controllers/user/views/edit.hbs +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - Edit {{user.name}} - - -

{{user.name}}

-
- - - -
- -
- - - -
- - diff --git a/examples/mvc/controllers/user/views/list.hbs b/examples/mvc/controllers/user/views/list.hbs deleted file mode 100644 index 448c66f8c7..0000000000 --- a/examples/mvc/controllers/user/views/list.hbs +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - Users - - -

Users

-

Click a user below to view their pets.

- - - diff --git a/examples/mvc/controllers/user/views/show.hbs b/examples/mvc/controllers/user/views/show.hbs deleted file mode 100644 index f3fccfe046..0000000000 --- a/examples/mvc/controllers/user/views/show.hbs +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - {{user.name}} - - -

{{user.name}} edit

- -{{#if hasMessages}} - -{{/if}} - -{{#if user.pets.length}} -

View {{user.name}}'s pets:

- -{{else}} -

No pets!

-{{/if}} - - diff --git a/examples/mvc/db.js b/examples/mvc/db.js deleted file mode 100644 index 94d1480f9b..0000000000 --- a/examples/mvc/db.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict' - -// faux database - -var pets = exports.pets = []; - -pets.push({ name: 'Tobi', id: 0 }); -pets.push({ name: 'Loki', id: 1 }); -pets.push({ name: 'Jane', id: 2 }); -pets.push({ name: 'Raul', id: 3 }); - -var users = exports.users = []; - -users.push({ name: 'TJ', pets: [pets[0], pets[1], pets[2]], id: 0 }); -users.push({ name: 'Guillermo', pets: [pets[3]], id: 1 }); -users.push({ name: 'Nathan', pets: [], id: 2 }); diff --git a/examples/mvc/index.js b/examples/mvc/index.js deleted file mode 100644 index da4727b282..0000000000 --- a/examples/mvc/index.js +++ /dev/null @@ -1,95 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../..'); -var logger = require('morgan'); -var path = require('path'); -var session = require('express-session'); -var methodOverride = require('method-override'); - -var app = module.exports = express(); - -// set our default template engine to "ejs" -// which prevents the need for using file extensions -app.set('view engine', 'ejs'); - -// set views for error and 404 pages -app.set('views', path.join(__dirname, 'views')); - -// define a custom res.message() method -// which stores messages in the session -app.response.message = function(msg){ - // reference `req.session` via the `this.req` reference - var sess = this.req.session; - // simply add the msg to an array for later - sess.messages = sess.messages || []; - sess.messages.push(msg); - return this; -}; - -// log -if (!module.parent) app.use(logger('dev')); - -// serve static files -app.use(express.static(path.join(__dirname, 'public'))); - -// session support -app.use(session({ - resave: false, // don't save session if unmodified - saveUninitialized: false, // don't create session until something stored - secret: 'some secret here' -})); - -// parse request bodies (req.body) -app.use(express.urlencoded({ extended: true })) - -// allow overriding methods in query (?_method=put) -app.use(methodOverride('_method')); - -// expose the "messages" local variable when views are rendered -app.use(function(req, res, next){ - var msgs = req.session.messages || []; - - // expose "messages" local variable - res.locals.messages = msgs; - - // expose "hasMessages" - res.locals.hasMessages = !! msgs.length; - - /* This is equivalent: - res.locals({ - messages: msgs, - hasMessages: !! msgs.length - }); - */ - - next(); - // empty or "flush" the messages so they - // don't build up - req.session.messages = []; -}); - -// load controllers -require('./lib/boot')(app, { verbose: !module.parent }); - -app.use(function(err, req, res, next){ - // log it - if (!module.parent) console.error(err.stack); - - // error page - res.status(500).render('5xx'); -}); - -// assume 404 since no middleware responded -app.use(function(req, res, next){ - res.status(404).render('404', { url: req.originalUrl }); -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/mvc/lib/boot.js b/examples/mvc/lib/boot.js deleted file mode 100644 index 0216e5d76d..0000000000 --- a/examples/mvc/lib/boot.js +++ /dev/null @@ -1,83 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../../..'); -var fs = require('fs'); -var path = require('path'); - -module.exports = function(parent, options){ - var dir = path.join(__dirname, '..', 'controllers'); - var verbose = options.verbose; - fs.readdirSync(dir).forEach(function(name){ - var file = path.join(dir, name) - if (!fs.statSync(file).isDirectory()) return; - verbose && console.log('\n %s:', name); - var obj = require(file); - var name = obj.name || name; - var prefix = obj.prefix || ''; - var app = express(); - var handler; - var method; - var url; - - // allow specifying the view engine - if (obj.engine) app.set('view engine', obj.engine); - app.set('views', path.join(__dirname, '..', 'controllers', name, 'views')); - - // generate routes based - // on the exported methods - for (var key in obj) { - // "reserved" exports - if (~['name', 'prefix', 'engine', 'before'].indexOf(key)) continue; - // route exports - switch (key) { - case 'show': - method = 'get'; - url = '/' + name + '/:' + name + '_id'; - break; - case 'list': - method = 'get'; - url = '/' + name + 's'; - break; - case 'edit': - method = 'get'; - url = '/' + name + '/:' + name + '_id/edit'; - break; - case 'update': - method = 'put'; - url = '/' + name + '/:' + name + '_id'; - break; - case 'create': - method = 'post'; - url = '/' + name; - break; - case 'index': - method = 'get'; - url = '/'; - break; - default: - /* istanbul ignore next */ - throw new Error('unrecognized route: ' + name + '.' + key); - } - - // setup - handler = obj[key]; - url = prefix + url; - - // before middleware support - if (obj.before) { - app[method](url, obj.before, handler); - verbose && console.log(' %s %s -> before -> %s', method.toUpperCase(), url, key); - } else { - app[method](url, handler); - verbose && console.log(' %s %s -> %s', method.toUpperCase(), url, key); - } - } - - // mount the app - parent.use(app); - }); -}; diff --git a/examples/mvc/public/style.css b/examples/mvc/public/style.css deleted file mode 100644 index 8a23f9d41c..0000000000 --- a/examples/mvc/public/style.css +++ /dev/null @@ -1,14 +0,0 @@ -body { - padding: 50px; - font: 16px "Helvetica Neue", Helvetica, Arial, sans-serif; -} -a { - color: #107aff; - text-decoration: none; -} -a:hover { - text-decoration: underline; -} -h1 a { - font-size: 16px; -} diff --git a/examples/mvc/views/404.ejs b/examples/mvc/views/404.ejs deleted file mode 100644 index 21a86f8a65..0000000000 --- a/examples/mvc/views/404.ejs +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - Not Found - - - -

404: Not Found

-

Sorry we can't find <%= url %>

- - diff --git a/examples/mvc/views/5xx.ejs b/examples/mvc/views/5xx.ejs deleted file mode 100644 index 190f580543..0000000000 --- a/examples/mvc/views/5xx.ejs +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - Internal Server Error - - - -

500: Internal Server Error

-

Looks like something blew up!

- - diff --git a/examples/online/index.js b/examples/online/index.js deleted file mode 100644 index 0b5fdffc86..0000000000 --- a/examples/online/index.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict' - -// install redis first: -// https://redis.io/ - -// then: -// $ npm install redis online -// $ redis-server - -/** - * Module dependencies. - */ - -var express = require('../..'); -var online = require('online'); -var redis = require('redis'); -var db = redis.createClient(); - -// online - -online = online(db); - -// app - -var app = express(); - -// activity tracking, in this case using -// the UA string, you would use req.user.id etc - -app.use(function(req, res, next){ - // fire-and-forget - online.add(req.headers['user-agent']); - next(); -}); - -/** - * List helper. - */ - -function list(ids) { - return ''; -} - -/** - * GET users online. - */ - -app.get('/', function(req, res, next){ - online.last(5, function(err, ids){ - if (err) return next(err); - res.send('

Users online: ' + ids.length + '

' + list(ids)); - }); -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/params/index.js b/examples/params/index.js deleted file mode 100644 index f3cd8457eb..0000000000 --- a/examples/params/index.js +++ /dev/null @@ -1,73 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var createError = require('http-errors') -var express = require('../../'); -var app = module.exports = express(); - -// Faux database - -var users = [ - { name: 'tj' } - , { name: 'tobi' } - , { name: 'loki' } - , { name: 'jane' } - , { name: 'bandit' } -]; - -// Convert :to and :from to integers - -app.param(['to', 'from'], function(req, res, next, num, name){ - req.params[name] = parseInt(num, 10); - if( isNaN(req.params[name]) ){ - next(createError(400, 'failed to parseInt '+num)); - } else { - next(); - } -}); - -// Load user by id - -app.param('user', function(req, res, next, id){ - if (req.user = users[id]) { - next(); - } else { - next(createError(404, 'failed to find user')); - } -}); - -/** - * GET index. - */ - -app.get('/', function(req, res){ - res.send('Visit /user/0 or /users/0-2'); -}); - -/** - * GET :user. - */ - -app.get('/user/:user', function (req, res) { - res.send('user ' + req.user.name); -}); - -/** - * GET users :from - :to. - */ - -app.get('/users/:from-:to', function (req, res) { - var from = req.params.from; - var to = req.params.to; - var names = users.map(function(user){ return user.name; }); - res.send('users ' + names.slice(from, to + 1).join(', ')); -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/resource/index.js b/examples/resource/index.js deleted file mode 100644 index ff1f6fe11f..0000000000 --- a/examples/resource/index.js +++ /dev/null @@ -1,95 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../../'); - -var app = module.exports = express(); - -// Ad-hoc example resource method - -app.resource = function(path, obj) { - this.get(path, obj.index); - this.get(path + '/:a..:b.:format?', function(req, res){ - var a = parseInt(req.params.a, 10); - var b = parseInt(req.params.b, 10); - var format = req.params.format; - obj.range(req, res, a, b, format); - }); - this.get(path + '/:id', obj.show); - this.delete(path + '/:id', function(req, res){ - var id = parseInt(req.params.id, 10); - obj.destroy(req, res, id); - }); -}; - -// Fake records - -var users = [ - { name: 'tj' } - , { name: 'ciaran' } - , { name: 'aaron' } - , { name: 'guillermo' } - , { name: 'simon' } - , { name: 'tobi' } -]; - -// Fake controller. - -var User = { - index: function(req, res){ - res.send(users); - }, - show: function(req, res){ - res.send(users[req.params.id] || { error: 'Cannot find user' }); - }, - destroy: function(req, res, id){ - var destroyed = id in users; - delete users[id]; - res.send(destroyed ? 'destroyed' : 'Cannot find user'); - }, - range: function(req, res, a, b, format){ - var range = users.slice(a, b + 1); - switch (format) { - case 'json': - res.send(range); - break; - case 'html': - default: - var html = ''; - res.send(html); - break; - } - } -}; - -// curl http://localhost:3000/users -- responds with all users -// curl http://localhost:3000/users/1 -- responds with user 1 -// curl http://localhost:3000/users/4 -- responds with error -// curl http://localhost:3000/users/1..3 -- responds with several users -// curl -X DELETE http://localhost:3000/users/1 -- deletes the user - -app.resource('/users', User); - -app.get('/', function(req, res){ - res.send([ - '

Examples:

' - ].join('\n')); -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/route-map/index.js b/examples/route-map/index.js deleted file mode 100644 index 2bc28bd4b2..0000000000 --- a/examples/route-map/index.js +++ /dev/null @@ -1,75 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var escapeHtml = require('escape-html') -var express = require('../../lib/express'); - -var verbose = process.env.NODE_ENV !== 'test' - -var app = module.exports = express(); - -app.map = function(a, route){ - route = route || ''; - for (var key in a) { - switch (typeof a[key]) { - // { '/path': { ... }} - case 'object': - app.map(a[key], route + key); - break; - // get: function(){ ... } - case 'function': - if (verbose) console.log('%s %s', key, route); - app[key](route, a[key]); - break; - } - } -}; - -var users = { - list: function(req, res){ - res.send('user list'); - }, - - get: function(req, res){ - res.send('user ' + escapeHtml(req.params.uid)) - }, - - delete: function(req, res){ - res.send('delete users'); - } -}; - -var pets = { - list: function(req, res){ - res.send('user ' + escapeHtml(req.params.uid) + '\'s pets') - }, - - delete: function(req, res){ - res.send('delete ' + escapeHtml(req.params.uid) + '\'s pet ' + escapeHtml(req.params.pid)) - } -}; - -app.map({ - '/users': { - get: users.list, - delete: users.delete, - '/:uid': { - get: users.get, - '/pets': { - get: pets.list, - '/:pid': { - delete: pets.delete - } - } - } - } -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/route-middleware/index.js b/examples/route-middleware/index.js deleted file mode 100644 index 44ec13a95b..0000000000 --- a/examples/route-middleware/index.js +++ /dev/null @@ -1,90 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../../lib/express'); - -var app = express(); - -// Example requests: -// curl http://localhost:3000/user/0 -// curl http://localhost:3000/user/0/edit -// curl http://localhost:3000/user/1 -// curl http://localhost:3000/user/1/edit (unauthorized since this is not you) -// curl -X DELETE http://localhost:3000/user/0 (unauthorized since you are not an admin) - -// Dummy users -var users = [ - { id: 0, name: 'tj', email: 'tj@vision-media.ca', role: 'member' } - , { id: 1, name: 'ciaran', email: 'ciaranj@gmail.com', role: 'member' } - , { id: 2, name: 'aaron', email: 'aaron.heckmann+github@gmail.com', role: 'admin' } -]; - -function loadUser(req, res, next) { - // You would fetch your user from the db - var user = users[req.params.id]; - if (user) { - req.user = user; - next(); - } else { - next(new Error('Failed to load user ' + req.params.id)); - } -} - -function andRestrictToSelf(req, res, next) { - // If our authenticated user is the user we are viewing - // then everything is fine :) - if (req.authenticatedUser.id === req.user.id) { - next(); - } else { - // You may want to implement specific exceptions - // such as UnauthorizedError or similar so that you - // can handle these can be special-cased in an error handler - // (view ./examples/pages for this) - next(new Error('Unauthorized')); - } -} - -function andRestrictTo(role) { - return function(req, res, next) { - if (req.authenticatedUser.role === role) { - next(); - } else { - next(new Error('Unauthorized')); - } - } -} - -// Middleware for faux authentication -// you would of course implement something real, -// but this illustrates how an authenticated user -// may interact with middleware - -app.use(function(req, res, next){ - req.authenticatedUser = users[0]; - next(); -}); - -app.get('/', function(req, res){ - res.redirect('/user/0'); -}); - -app.get('/user/:id', loadUser, function(req, res){ - res.send('Viewing user ' + req.user.name); -}); - -app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){ - res.send('Editing user ' + req.user.name); -}); - -app.delete('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){ - res.send('Deleted user ' + req.user.name); -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/route-separation/index.js b/examples/route-separation/index.js deleted file mode 100644 index 5d48381111..0000000000 --- a/examples/route-separation/index.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../..'); -var path = require('path'); -var app = express(); -var logger = require('morgan'); -var cookieParser = require('cookie-parser'); -var methodOverride = require('method-override'); -var site = require('./site'); -var post = require('./post'); -var user = require('./user'); - -module.exports = app; - -// Config - -app.set('view engine', 'ejs'); -app.set('views', path.join(__dirname, 'views')); - -/* istanbul ignore next */ -if (!module.parent) { - app.use(logger('dev')); -} - -app.use(methodOverride('_method')); -app.use(cookieParser()); -app.use(express.urlencoded({ extended: true })) -app.use(express.static(path.join(__dirname, 'public'))); - -// General - -app.get('/', site.index); - -// User - -app.get('/users', user.list); -app.all('/user/:id/:op?', user.load); -app.get('/user/:id', user.view); -app.get('/user/:id/view', user.view); -app.get('/user/:id/edit', user.edit); -app.put('/user/:id/edit', user.update); - -// Posts - -app.get('/posts', post.list); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/route-separation/post.js b/examples/route-separation/post.js deleted file mode 100644 index 3a8e3a2d22..0000000000 --- a/examples/route-separation/post.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict' - -// Fake posts database - -var posts = [ - { title: 'Foo', body: 'some foo bar' }, - { title: 'Foo bar', body: 'more foo bar' }, - { title: 'Foo bar baz', body: 'more foo bar baz' } -]; - -exports.list = function(req, res){ - res.render('posts', { title: 'Posts', posts: posts }); -}; diff --git a/examples/route-separation/public/style.css b/examples/route-separation/public/style.css deleted file mode 100644 index d699784c60..0000000000 --- a/examples/route-separation/public/style.css +++ /dev/null @@ -1,24 +0,0 @@ -body { - padding: 50px; - font: 14px "Helvetica Neue", Arial, sans-serif; -} -a { - color: #00AEFF; - text-decoration: none; -} -a.edit { - color: #000; - opacity: .3; -} -a.edit::before { - content: ' ['; -} -a.edit::after { - content: ']'; -} -dt { - font-weight: bold; -} -dd { - margin: 15px; -} \ No newline at end of file diff --git a/examples/route-separation/site.js b/examples/route-separation/site.js deleted file mode 100644 index aee36d1bd7..0000000000 --- a/examples/route-separation/site.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict' - -exports.index = function(req, res){ - res.render('index', { title: 'Route Separation Example' }); -}; diff --git a/examples/route-separation/user.js b/examples/route-separation/user.js deleted file mode 100644 index 1c2aec7cd2..0000000000 --- a/examples/route-separation/user.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict' - -// Fake user database - -var users = [ - { name: 'TJ', email: 'tj@vision-media.ca' }, - { name: 'Tobi', email: 'tobi@vision-media.ca' } -]; - -exports.list = function(req, res){ - res.render('users', { title: 'Users', users: users }); -}; - -exports.load = function(req, res, next){ - var id = req.params.id; - req.user = users[id]; - if (req.user) { - next(); - } else { - var err = new Error('cannot find user ' + id); - err.status = 404; - next(err); - } -}; - -exports.view = function(req, res){ - res.render('users/view', { - title: 'Viewing user ' + req.user.name, - user: req.user - }); -}; - -exports.edit = function(req, res){ - res.render('users/edit', { - title: 'Editing user ' + req.user.name, - user: req.user - }); -}; - -exports.update = function(req, res){ - // Normally you would handle all kinds of - // validation and save back to the db - var user = req.body.user; - req.user.name = user.name; - req.user.email = user.email; - res.redirect('back'); -}; diff --git a/examples/route-separation/views/footer.ejs b/examples/route-separation/views/footer.ejs deleted file mode 100644 index 308b1d01b6..0000000000 --- a/examples/route-separation/views/footer.ejs +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/examples/route-separation/views/header.ejs b/examples/route-separation/views/header.ejs deleted file mode 100644 index 4300325e0a..0000000000 --- a/examples/route-separation/views/header.ejs +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - <%= title %> - - - diff --git a/examples/route-separation/views/index.ejs b/examples/route-separation/views/index.ejs deleted file mode 100644 index 7fd75879c1..0000000000 --- a/examples/route-separation/views/index.ejs +++ /dev/null @@ -1,10 +0,0 @@ -<%- include('header') -%> - -

<%= title %>

- - - -<%- include('footer') -%> diff --git a/examples/route-separation/views/posts/index.ejs b/examples/route-separation/views/posts/index.ejs deleted file mode 100644 index cbcebffebf..0000000000 --- a/examples/route-separation/views/posts/index.ejs +++ /dev/null @@ -1,12 +0,0 @@ -<%- include('../header') -%> - -

Posts

- -
- <% posts.forEach(function(post) { %> -
<%= post.title %>
-
<%= post.body %>
- <% }) %> -
- -<%- include('../footer') -%> diff --git a/examples/route-separation/views/users/edit.ejs b/examples/route-separation/views/users/edit.ejs deleted file mode 100644 index 6df78a953a..0000000000 --- a/examples/route-separation/views/users/edit.ejs +++ /dev/null @@ -1,23 +0,0 @@ -<%- include('../header') -%> - -

Editing <%= user.name %>

- -
-
-

- Name: - -

- -

- Email: - -

- -

- -

-
-
- -<%- include('../footer') -%> diff --git a/examples/route-separation/views/users/index.ejs b/examples/route-separation/views/users/index.ejs deleted file mode 100644 index 949412a21e..0000000000 --- a/examples/route-separation/views/users/index.ejs +++ /dev/null @@ -1,14 +0,0 @@ -<%- include('../header') -%> - -

<%= title %>

- -
- <% users.forEach(function(user, index) { %> -
  • - <%= user.name %> - edit -
  • - <% }) %> -
    - -<%- include('../footer') -%> diff --git a/examples/route-separation/views/users/view.ejs b/examples/route-separation/views/users/view.ejs deleted file mode 100644 index 457bd5399f..0000000000 --- a/examples/route-separation/views/users/view.ejs +++ /dev/null @@ -1,9 +0,0 @@ -<%- include('../header') -%> - -

    <%= user.name %>

    - -
    -

    Email: <%= user.email %>

    -
    - -<%- include('../footer') -%> diff --git a/examples/search/index.js b/examples/search/index.js deleted file mode 100644 index 0d19444e52..0000000000 --- a/examples/search/index.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict' - -// install redis first: -// https://redis.io/ - -// then: -// $ npm install redis -// $ redis-server - -/** - * Module dependencies. - */ - -var express = require('../..'); -var path = require('path'); -var redis = require('redis'); - -var db = redis.createClient(); - -// npm install redis - -var app = express(); - -app.use(express.static(path.join(__dirname, 'public'))); - -// populate search - -db.sadd('ferret', 'tobi'); -db.sadd('ferret', 'loki'); -db.sadd('ferret', 'jane'); -db.sadd('cat', 'manny'); -db.sadd('cat', 'luna'); - -/** - * GET search for :query. - */ - -app.get('/search/:query?', function(req, res){ - var query = req.params.query; - db.smembers(query, function(err, vals){ - if (err) return res.send(500); - res.send(vals); - }); -}); - -/** - * GET client javascript. Here we use sendFile() - * because serving __dirname with the static() middleware - * would also mean serving our server "index.js" and the "search.jade" - * template. - */ - -app.get('/client.js', function(req, res){ - res.sendFile(path.join(__dirname, 'client.js')); -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/search/public/client.js b/examples/search/public/client.js deleted file mode 100644 index cd43faf71e..0000000000 --- a/examples/search/public/client.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict' - -var search = document.querySelector('[type=search]'); -var code = document.querySelector('pre'); - -search.addEventListener('keyup', function(){ - var xhr = new XMLHttpRequest; - xhr.open('GET', '/search/' + search.value, true); - xhr.onreadystatechange = function(){ - if (xhr.readyState === 4) { - code.textContent = xhr.responseText; - } - }; - xhr.send(); -}, false); diff --git a/examples/search/public/index.html b/examples/search/public/index.html deleted file mode 100644 index 7353644ba6..0000000000 --- a/examples/search/public/index.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - Search example - - - -

    Search

    -

    Try searching for "ferret" or "cat".

    - -
    
    -  
    -
    -
    diff --git a/examples/session/index.js b/examples/session/index.js
    deleted file mode 100644
    index 2bb2b109c8..0000000000
    --- a/examples/session/index.js
    +++ /dev/null
    @@ -1,37 +0,0 @@
    -'use strict'
    -
    -// install redis first:
    -// https://redis.io/
    -
    -// then:
    -// $ npm install redis
    -// $ redis-server
    -
    -var express = require('../..');
    -var session = require('express-session');
    -
    -var app = express();
    -
    -// Populates req.session
    -app.use(session({
    -  resave: false, // don't save session if unmodified
    -  saveUninitialized: false, // don't create session until something stored
    -  secret: 'keyboard cat'
    -}));
    -
    -app.get('/', function(req, res){
    -  var body = '';
    -  if (req.session.views) {
    -    ++req.session.views;
    -  } else {
    -    req.session.views = 1;
    -    body += '

    First time visiting? view this page in several browsers :)

    '; - } - res.send(body + '

    viewed ' + req.session.views + ' times.

    '); -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/session/redis.js b/examples/session/redis.js deleted file mode 100644 index bbbdc7fd3e..0000000000 --- a/examples/session/redis.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../..'); -var logger = require('morgan'); -var session = require('express-session'); - -// pass the express to the connect redis module -// allowing it to inherit from session.Store -var RedisStore = require('connect-redis')(session); - -var app = express(); - -app.use(logger('dev')); - -// Populates req.session -app.use(session({ - resave: false, // don't save session if unmodified - saveUninitialized: false, // don't create session until something stored - secret: 'keyboard cat', - store: new RedisStore -})); - -app.get('/', function(req, res){ - var body = ''; - if (req.session.views) { - ++req.session.views; - } else { - req.session.views = 1; - body += '

    First time visiting? view this page in several browsers :)

    '; - } - res.send(body + '

    viewed ' + req.session.views + ' times.

    '); -}); - -app.listen(3000); -console.log('Express app started on port 3000'); diff --git a/examples/static-files/index.js b/examples/static-files/index.js deleted file mode 100644 index 609c546b47..0000000000 --- a/examples/static-files/index.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../..'); -var logger = require('morgan'); -var path = require('path'); -var app = express(); - -// log requests -app.use(logger('dev')); - -// express on its own has no notion -// of a "file". The express.static() -// middleware checks for a file matching -// the `req.path` within the directory -// that you pass it. In this case "GET /js/app.js" -// will look for "./public/js/app.js". - -app.use(express.static(path.join(__dirname, 'public'))); - -// if you wanted to "prefix" you may use -// the mounting feature of Connect, for example -// "GET /static/js/app.js" instead of "GET /js/app.js". -// The mount-path "/static" is simply removed before -// passing control to the express.static() middleware, -// thus it serves the file correctly by ignoring "/static" -app.use('/static', express.static(path.join(__dirname, 'public'))); - -// if for some reason you want to serve files from -// several directories, you can use express.static() -// multiple times! Here we're passing "./public/css", -// this will allow "GET /style.css" instead of "GET /css/style.css": -app.use(express.static(path.join(__dirname, 'public', 'css'))); - -app.listen(3000); -console.log('listening on port 3000'); -console.log('try:'); -console.log(' GET /hello.txt'); -console.log(' GET /js/app.js'); -console.log(' GET /css/style.css'); diff --git a/examples/static-files/public/css/style.css b/examples/static-files/public/css/style.css deleted file mode 100644 index 7fc28f96c4..0000000000 --- a/examples/static-files/public/css/style.css +++ /dev/null @@ -1,3 +0,0 @@ -body { - -} \ No newline at end of file diff --git a/examples/static-files/public/hello.txt b/examples/static-files/public/hello.txt deleted file mode 100644 index 2b31011cf9..0000000000 --- a/examples/static-files/public/hello.txt +++ /dev/null @@ -1 +0,0 @@ -hey \ No newline at end of file diff --git a/examples/static-files/public/js/app.js b/examples/static-files/public/js/app.js deleted file mode 100644 index 775eb734b0..0000000000 --- a/examples/static-files/public/js/app.js +++ /dev/null @@ -1 +0,0 @@ -// foo diff --git a/examples/vhost/index.js b/examples/vhost/index.js deleted file mode 100644 index a9499356b4..0000000000 --- a/examples/vhost/index.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../..'); -var logger = require('morgan'); -var vhost = require('vhost'); - -/* -edit /etc/hosts: - -127.0.0.1 foo.example.com -127.0.0.1 bar.example.com -127.0.0.1 example.com -*/ - -// Main server app - -var main = express(); - -if (!module.parent) main.use(logger('dev')); - -main.get('/', function(req, res){ - res.send('Hello from main app!'); -}); - -main.get('/:sub', function(req, res){ - res.send('requested ' + req.params.sub); -}); - -// Redirect app - -var redirect = express(); - -redirect.use(function(req, res){ - if (!module.parent) console.log(req.vhost); - res.redirect('http://example.com:3000/' + req.vhost[0]); -}); - -// Vhost app - -var app = module.exports = express(); - -app.use(vhost('*.example.com', redirect)); // Serves all subdomains via Redirect app -app.use(vhost('example.com', main)); // Serves top level domain via Main server app - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/view-constructor/github-view.js b/examples/view-constructor/github-view.js deleted file mode 100644 index 43d29336ca..0000000000 --- a/examples/view-constructor/github-view.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var https = require('https'); -var path = require('path'); -var extname = path.extname; - -/** - * Expose `GithubView`. - */ - -module.exports = GithubView; - -/** - * Custom view that fetches and renders - * remove github templates. You could - * render templates from a database etc. - */ - -function GithubView(name, options){ - this.name = name; - options = options || {}; - this.engine = options.engines[extname(name)]; - // "root" is the app.set('views') setting, however - // in your own implementation you could ignore this - this.path = '/' + options.root + '/master/' + name; -} - -/** - * Render the view. - */ - -GithubView.prototype.render = function(options, fn){ - var self = this; - var opts = { - host: 'raw.githubusercontent.com', - port: 443, - path: this.path, - method: 'GET' - }; - - https.request(opts, function(res) { - var buf = ''; - res.setEncoding('utf8'); - res.on('data', function(str){ buf += str }); - res.on('end', function(){ - self.engine(buf, options, fn); - }); - }).end(); -}; diff --git a/examples/view-constructor/index.js b/examples/view-constructor/index.js deleted file mode 100644 index 3d673670e3..0000000000 --- a/examples/view-constructor/index.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../../'); -var GithubView = require('./github-view'); -var md = require('marked').parse; - -var app = module.exports = express(); - -// register .md as an engine in express view system -app.engine('md', function(str, options, fn){ - try { - var html = md(str); - html = html.replace(/\{([^}]+)\}/g, function(_, name){ - return options[name] || ''; - }); - fn(null, html); - } catch(err) { - fn(err); - } -}); - -// pointing to a particular github repo to load files from it -app.set('views', 'expressjs/express'); - -// register a new view constructor -app.set('view', GithubView); - -app.get('/', function(req, res){ - // rendering a view relative to the repo. - // app.locals, res.locals, and locals passed - // work like they normally would - res.render('examples/markdown/views/index.md', { title: 'Example' }); -}); - -app.get('/Readme.md', function(req, res){ - // rendering a view from https://github.com/expressjs/express/blob/master/Readme.md - res.render('Readme.md'); -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/view-locals/index.js b/examples/view-locals/index.js deleted file mode 100644 index a2af24f355..0000000000 --- a/examples/view-locals/index.js +++ /dev/null @@ -1,155 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../..'); -var path = require('path'); -var User = require('./user'); -var app = express(); - -app.set('views', path.join(__dirname, 'views')); -app.set('view engine', 'ejs'); - -// filter ferrets only - -function ferrets(user) { - return user.species === 'ferret' -} - -// naive nesting approach, -// delegating errors to next(err) -// in order to expose the "count" -// and "users" locals - -app.get('/', function(req, res, next){ - User.count(function(err, count){ - if (err) return next(err); - User.all(function(err, users){ - if (err) return next(err); - res.render('index', { - title: 'Users', - count: count, - users: users.filter(ferrets) - }); - }) - }) -}); - - - - -// this approach is cleaner, -// less nesting and we have -// the variables available -// on the request object - -function count(req, res, next) { - User.count(function(err, count){ - if (err) return next(err); - req.count = count; - next(); - }) -} - -function users(req, res, next) { - User.all(function(err, users){ - if (err) return next(err); - req.users = users; - next(); - }) -} - -app.get('/middleware', count, users, function (req, res) { - res.render('index', { - title: 'Users', - count: req.count, - users: req.users.filter(ferrets) - }); -}); - - - - -// this approach is much like the last -// however we're explicitly exposing -// the locals within each middleware -// -// note that this may not always work -// well, for example here we filter -// the users in the middleware, which -// may not be ideal for our application. -// so in that sense the previous example -// is more flexible with `req.users`. - -function count2(req, res, next) { - User.count(function(err, count){ - if (err) return next(err); - res.locals.count = count; - next(); - }) -} - -function users2(req, res, next) { - User.all(function(err, users){ - if (err) return next(err); - res.locals.users = users.filter(ferrets); - next(); - }) -} - -app.get('/middleware-locals', count2, users2, function (req, res) { - // you can see now how we have much less - // to pass to res.render(). If we have - // several routes related to users this - // can be a great productivity booster - res.render('index', { title: 'Users' }); -}); - -// keep in mind that middleware may be placed anywhere -// and in various combinations, so if you have locals -// that you wish to make available to all subsequent -// middleware/routes you can do something like this: - -/* - -app.use(function(req, res, next){ - res.locals.user = req.user; - res.locals.sess = req.session; - next(); -}); - -*/ - -// or suppose you have some /admin -// "global" local variables: - -/* - -app.use('/api', function(req, res, next){ - res.locals.user = req.user; - res.locals.sess = req.session; - next(); -}); - -*/ - -// the following is effectively the same, -// but uses a route instead: - -/* - -app.all('/api/*', function(req, res, next){ - res.locals.user = req.user; - res.locals.sess = req.session; - next(); -}); - -*/ - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} diff --git a/examples/view-locals/user.js b/examples/view-locals/user.js deleted file mode 100644 index aaa6f85ff0..0000000000 --- a/examples/view-locals/user.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict' - -module.exports = User; - -// faux model - -function User(name, age, species) { - this.name = name; - this.age = age; - this.species = species; -} - -User.all = function(fn){ - // process.nextTick makes sure this function API - // behaves in an asynchronous manner, like if it - // was a real DB query to read all users. - process.nextTick(function(){ - fn(null, users); - }); -}; - -User.count = function(fn){ - process.nextTick(function(){ - fn(null, users.length); - }); -}; - -// faux database - -var users = []; - -users.push(new User('Tobi', 2, 'ferret')); -users.push(new User('Loki', 1, 'ferret')); -users.push(new User('Jane', 6, 'ferret')); -users.push(new User('Luna', 1, 'cat')); -users.push(new User('Manny', 1, 'cat')); diff --git a/examples/view-locals/views/index.ejs b/examples/view-locals/views/index.ejs deleted file mode 100644 index 287f34bc28..0000000000 --- a/examples/view-locals/views/index.ejs +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - <%= title %> - - - -

    <%= title %>

    - <% users.forEach(function(user) { %> -
  • <%= user.name %> is a <% user.age %> year old <%= user.species %>
  • - <% }); %> - - diff --git a/examples/web-service/index.js b/examples/web-service/index.js deleted file mode 100644 index d1a9036215..0000000000 --- a/examples/web-service/index.js +++ /dev/null @@ -1,117 +0,0 @@ -'use strict' - -/** - * Module dependencies. - */ - -var express = require('../../'); - -var app = module.exports = express(); - -// create an error with .status. we -// can then use the property in our -// custom error handler (Connect respects this prop as well) - -function error(status, msg) { - var err = new Error(msg); - err.status = status; - return err; -} - -// if we wanted to supply more than JSON, we could -// use something similar to the content-negotiation -// example. - -// here we validate the API key, -// by mounting this middleware to /api -// meaning only paths prefixed with "/api" -// will cause this middleware to be invoked - -app.use('/api', function(req, res, next){ - var key = req.query['api-key']; - - // key isn't present - if (!key) return next(error(400, 'api key required')); - - // key is invalid - if (apiKeys.indexOf(key) === -1) return next(error(401, 'invalid api key')) - - // all good, store req.key for route access - req.key = key; - next(); -}); - -// map of valid api keys, typically mapped to -// account info with some sort of database like redis. -// api keys do _not_ serve as authentication, merely to -// track API usage or help prevent malicious behavior etc. - -var apiKeys = ['foo', 'bar', 'baz']; - -// these two objects will serve as our faux database - -var repos = [ - { name: 'express', url: 'https://github.com/expressjs/express' }, - { name: 'stylus', url: 'https://github.com/learnboost/stylus' }, - { name: 'cluster', url: 'https://github.com/learnboost/cluster' } -]; - -var users = [ - { name: 'tobi' } - , { name: 'loki' } - , { name: 'jane' } -]; - -var userRepos = { - tobi: [repos[0], repos[1]] - , loki: [repos[1]] - , jane: [repos[2]] -}; - -// we now can assume the api key is valid, -// and simply expose the data - -// example: http://localhost:3000/api/users/?api-key=foo -app.get('/api/users', function (req, res) { - res.send(users); -}); - -// example: http://localhost:3000/api/repos/?api-key=foo -app.get('/api/repos', function (req, res) { - res.send(repos); -}); - -// example: http://localhost:3000/api/user/tobi/repos/?api-key=foo -app.get('/api/user/:name/repos', function(req, res, next){ - var name = req.params.name; - var user = userRepos[name]; - - if (user) res.send(user); - else next(); -}); - -// middleware with an arity of 4 are considered -// error handling middleware. When you next(err) -// it will be passed through the defined middleware -// in order, but ONLY those with an arity of 4, ignoring -// regular middleware. -app.use(function(err, req, res, next){ - // whatever you want here, feel free to populate - // properties on `err` to treat it differently in here. - res.status(err.status || 500); - res.send({ error: err.message }); -}); - -// our custom JSON 404 middleware. Since it's placed last -// it will be the last middleware called, if all others -// invoke next() and do not respond. -app.use(function(req, res){ - res.status(404); - res.send({ error: "Sorry, can't find that" }) -}); - -/* istanbul ignore next */ -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -}