index.js
This file
Path
examples/params/index.js
80 lines · 1.4 KiB · JavaScript
Last changed by
examples: use strict modeDouglas Christopher Wilsonbefore adoption20047bb
History of this fileTake it
The walk stopped after 200 commits: lines older than 76bf96e point at it.
examples: use strict modeDouglas Christopher Wilsonbefore adoption20047bb
lines 1–2why, one step back1'use strict'2deps: finalhandler@1.1.1Douglas Christopher Wilsonbefore adoption76bf96e
lines 3–12why, one step back3/**4 * Module dependencies.5 */67var express = require('../../');8var app = module.exports = express();910// Faux database1112var users = [build: eslint@4.19.1Douglas Christopher Wilsonbefore adoptionde081eb
line 13why, one step back13 { name: 'tj' }deps: finalhandler@1.1.1Douglas Christopher Wilsonbefore adoption76bf96e
lines 14–80why, one step back14 , { name: 'tobi' }15 , { name: 'loki' }16 , { name: 'jane' }17 , { name: 'bandit' }18];1920// Create HTTP error2122function createError(status, message) {23 var err = new Error(message);24 err.status = status;25 return err;26}2728// Convert :to and :from to integers2930app.param(['to', 'from'], function(req, res, next, num, name){31 req.params[name] = parseInt(num, 10);32 if( isNaN(req.params[name]) ){33 next(createError(400, 'failed to parseInt '+num));34 } else {35 next();36 }37});3839// Load user by id4041app.param('user', function(req, res, next, id){42 if (req.user = users[id]) {43 next();44 } else {45 next(createError(404, 'failed to find user'));46 }47});4849/**50 * GET index.51 */5253app.get('/', function(req, res){54 res.send('Visit /user/0 or /users/0-2');55});5657/**58 * GET :user.59 */6061app.get('/user/:user', function(req, res, next){62 res.send('user ' + req.user.name);63});6465/**66 * GET users :from - :to.67 */6869app.get('/users/:from-:to', function(req, res, next){70 var from = req.params.from;71 var to = req.params.to;72 var names = users.map(function(user){ return user.name; });73 res.send('users ' + names.slice(from, to + 1).join(', '));74});7576/* istanbul ignore next */77if (!module.parent) {78 app.listen(3000);79 console.log('Express started on port 3000');80}