index.js
This file
Path
examples/params/index.js
78 lines · 1.4 KiB · JavaScript
Last changed by
Merge tag '3.20.3'Douglas Christopher Wilsonbefore adoption62d5c38
History of this fileTake it
examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
lines 1–17why, one step back1/**2 * Module dependencies.3 */45var express = require('../../');6var app = module.exports = express();78// Faux database910var users = [11 { name: 'tj' }12 , { name: 'tobi' }13 , { name: 'loki' }14 , { name: 'jane' }15 , { name: 'bandit' }16];17Merge tag '3.20.3'Douglas Christopher Wilsonbefore adoption62d5c38
lines 18–25why, one step back18// Create HTTP error1920function createError(status, message) {21 var err = new Error(message);22 err.status = status;23 return err;24}25examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
lines 26–30why, one step back26// Convert :to and :from to integers2728app.param(['to', 'from'], function(req, res, next, num, name){29 req.params[name] = parseInt(num, 10);30 if( isNaN(req.params[name]) ){Merge tag '3.20.3'Douglas Christopher Wilsonbefore adoption62d5c38
line 31why, one step back31 next(createError(400, 'failed to parseInt '+num));examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
lines 32–42why, one step back32 } else {33 next();34 }35});3637// Load user by id3839app.param('user', function(req, res, next, id){40 if (req.user = users[id]) {41 next();42 } else {Merge tag '3.20.3'Douglas Christopher Wilsonbefore adoption62d5c38
line 43why, one step back43 next(createError(404, 'failed to find user'));examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
lines 44–78why, one step back44 }45});4647/**48 * GET index.49 */5051app.get('/', function(req, res){52 res.send('Visit /user/0 or /users/0-2');53});5455/**56 * GET :user.57 */5859app.get('/user/:user', function(req, res, next){60 res.send('user ' + req.user.name);61});6263/**64 * GET users :from - :to.65 */6667app.get('/users/:from-:to', function(req, res, next){68 var from = req.params.from;69 var to = req.params.to;70 var names = users.map(function(user){ return user.name; });71 res.send('users ' + names.slice(from, to).join(', '));72});7374/* istanbul ignore next */75if (!module.parent) {76 app.listen(3000);77 console.log('Express started on port 3000');78}