Using a Router Instance

Let's refactor app.js to use a Router object.

Create a new router object and assign it to the router variable.

var router = express.Router();

When we are done, our router will be mounted on the /cities path. With this in mind, change app.route('/cities') to use router and map requests to the root path.

app.route('/cities')
.get(function (request, response) {
if(request.query.search){
response.json(citySearch(request.query.search));
}else{
response.json(cities);
}
}) //to router.route('/')
.get(function (request, response) {
if(request.query.search){
response.json(citySearch(request.query.search));
}else{
response.json(cities);
}
})

Likewise, let's move our '/cities/:name' route to our router. Remember to update the path.

app.route('/cities/:name')
.get(function (request, response) {
var cityInfo = cities[request.cityName];
if(cityInfo){
response.json(cityInfo);
}else{
response.status(404).json("City not found");
}
}) .delete(function (request, response) {
if(cities[request.cityName]){
delete cities[request.cityName];
response.sendStatus(200);
}else{
response.sendStatus(404);
}
}); //to router.route('/:name')
.get(function (request, response) {
var cityInfo = cities[request.cityName];
if(cityInfo){
response.json(cityInfo);
}else{
response.status(404).json("City not found");
}
}) .delete(function (request, response) {
if(cities[request.cityName]){
delete cities[request.cityName];
response.sendStatus(200);
}else{
response.sendStatus(404);
}
});

Our router is now ready to be used by app. Mount our new router under the /cities path.

app.use('/cities', router);
var express = require('express');
var app = express(); var bodyParser = require('body-parser');
var parseUrlencoded = bodyParser.urlencoded({ extended: false }); // In memory store for the
// cities in our application
var cities = {
'Lotopia': 'Rough and mountainous',
'Caspiana': 'Sky-top island',
'Indigo': 'Vibrant and thriving',
'Paradise': 'Lush, green plantation',
'Flotilla': 'Bustling urban oasis'
}; app.param('name', function (request, response, next) {
request.cityName = parseCityName(request.params.name);
}); var router = express.Router();
app.use('/cities', router);
router.route('/')
.get(function (request, response) {
if(request.query.search){
response.json(citySearch(request.query.search));
}else{
response.json(cities);
}
}) .post(parseUrlencoded, function (request, response) {
if(request.body.description.length > 4){
var city = createCity(request.body.name, request.body.description);
response.status(201).json(city);
}else{
response.status(400).json('Invalid City');
}
}); router.route('/:name')
.get(function (request, response) {
var cityInfo = cities[request.cityName];
if(cityInfo){
response.json(cityInfo);
}else{
response.status(404).json("City not found");
}
}) .delete(function (request, response) {
if(cities[request.cityName]){
delete cities[request.cityName];
response.sendStatus(200);
}else{
response.sendStatus(404);
}
}); // Searches for keyword in description
// and returns the city
function citySearch(keyword) {
var regexp = RegExp(keyword, 'i');
var result = cities.filter(function (city) {
return city.match(regexp);
}); return result;
} // Adds a new city to the
// in memory store
function createCity(name, description){
cities[name] = description;
return name;
} // Uppercase the city name.
function parseCityName(name){
var parsedName = name[0].toUpperCase() + name.slice(1).toLowerCase();
return parsedName;
} app.listen(3000);

All HTTP Verbs

What function would you call to match all HTTP verbs?

Answer:

app.all();

Using All

Let's use the app.all() method to handle the name parameter instead of app.param().

Add a call to all() for our router's '/:name' route. Pass a callback function that accepts requestresponse, and next.

router.route('/:name')
.all(function(request, response, next){ })

Now let's take our logic from the callback function passed to app.param()and move it to our all() callback.

router.route('/:name')
.all(function(request, response, next){
request.cityName = parseCityName(request.params.name);
})
var express = require('express');
var app = express(); var bodyParser = require('body-parser');
var parseUrlencoded = bodyParser.urlencoded({ extended: false }); // In memory store for the cities in our application
var cities = {
'Lotopia': 'Rough and mountainous',
'Caspiana': 'Sky-top island',
'Indigo': 'Vibrant and thriving',
'Paradise': 'Lush, green plantation',
'Flotilla': 'Bustling urban oasis'
}; // Searches for keyword in description and returns the city
function citySearch(keyword) {
var regexp = RegExp(keyword, 'i');
var result = cities.filter(function (city) {
return city.match(regexp);
}); return result;
} // Adds a new city to the in memory store
function createCity(name, description) {
cities[name] = description;
return name;
} // Uppercase the city name.
function parseCityName(name) {
var parsedName = name[0].toUpperCase() + name.slice(1).toLowerCase();
return parsedName;
} var router = express.Router(); router.route('/')
.get(function (request, response) {
if(request.query.search) {
response.json(citySearch(request.query.search));
} else {
response.json(cities);
}
}) .post(parseUrlencoded, function (request, response) {
if(request.body.description.length > 4) {
var city = createCity(request.body.name, request.body.description);
response.status(201).json(city);
} else {
response.status(400).json('Invalid City');
}
}); router.route('/:name')
.all(function(request, response, next){
request.cityName = parseCityName(request.params.name);
})
.get(function (request, response) {
var cityInfo = cities[request.cityName];
if(cityInfo) {
response.json(cityInfo);
} else {
response.status(404).json("City not found");
}
}) .delete(function (request, response) {
if(cities[request.cityName]) {
delete cities[request.cityName];
response.sendStatus(200);
} else {
response.sendStatus(404);
}
}); app.use('/cities', router); app.listen(3000);

Creating a Router Module

Our single application file is growing too long. It's time we extract our routes to a separate Node module under the routes folder.

Move our router and its supporting code from app.js toroutes/cities.js.

routes/cities.js

var bodyParser = require('body-parser');
var parseUrlencoded = bodyParser.urlencoded({ extended: false }); // In memory store for the
// cities in our application
var cities = {
'Lotopia': 'Rough and mountainous',
'Caspiana': 'Sky-top island',
'Indigo': 'Vibrant and thriving',
'Paradise': 'Lush, green plantation',
'Flotilla': 'Bustling urban oasis'
}; var router = express.Router(); router.route('/')
.get(function (request, response) {
if(request.query.search){
response.json(citySearch(request.query.search));
}else{
response.json(cities);
}
}) .post(parseUrlencoded, function (request, response) {
if(request.body.description.length > 4){
var city = createCity(request.body.name, request.body.description);
response.status(201).json(city);
}else{
response.status(400).json('Invalid City');
}
}); router.route('/:name')
.all(function (request, response, next) {
request.cityName = parseCityName(request.params.name);
}) .get(function (request, response) {
var cityInfo = cities[request.cityName];
if(cityInfo){
response.json(cityInfo);
}else{
response.status(404).json("City not found");
}
}) .delete(function (request, response) {
if(cities[request.cityName]){
delete cities[request.cityName];
response.sendStatus(200);
}else{
response.sendStatus(404);
}
}); // Searches for keyword in description
// and returns the city
function citySearch(keyword) {
var regexp = RegExp(keyword, 'i');
var result = cities.filter(function (city) {
return city.match(regexp);
}); return result;
} // Adds a new city to the
// in memory store
function createCity(name, description){
cities[name] = description;
return name;
} // Uppercase the city name.
function parseCityName(name){
var parsedName = name[0].toUpperCase() + name.slice(1).toLowerCase();
return parsedName;
}

export our router object so other files can have access to it. Remember, Node - therefore Express - uses the CommonJS module specification.

module.exports = router;

Our cities routes module is now ready to be used from app.js. Require the new routes/cities module from app.js and assign it to a variable calledrouter;

app.js

var router = require('./routes/cities');

app.js

var express = require('express');
var app = express();
var router = require('./routes/cities'); app.use('/cities', router);
app.listen(3000);

routes/cities.js

var express = require('express');
var bodyParser = require('body-parser');
var parseUrlencoded = bodyParser.urlencoded({ extended: false }); // In memory store for the
// cities in our application
var cities = {
'Lotopia': 'Rough and mountainous',
'Caspiana': 'Sky-top island',
'Indigo': 'Vibrant and thriving',
'Paradise': 'Lush, green plantation',
'Flotilla': 'Bustling urban oasis'
}; var router = express.Router(); router.route('/')
.get(function (request, response) {
if(request.query.search){
response.json(citySearch(request.query.search));
}else{
response.json(cities);
}
}) .post(parseUrlencoded, function (request, response) {
if(request.body.description.length > 4){
var city = createCity(request.body.name, request.body.description);
response.status(201).json(city);
}else{
response.status(400).json('Invalid City');
}
}); router.route('/:name')
.all(function (request, response, next) {
request.cityName = parseCityName(request.params.name);
}) .get(function (request, response) {
var cityInfo = cities[request.cityName];
if(cityInfo){
response.json(cityInfo);
}else{
response.status(404).json("City not found");
}
}) .delete(function (request, response) {
if(cities[request.cityName]){
delete cities[request.cityName];
response.sendStatus(200);
}else{
response.sendStatus(404);
}
}); // Searches for keyword in description
// and returns the city
function citySearch(keyword) {
var regexp = RegExp(keyword, 'i');
var result = cities.filter(function (city) {
return city.match(regexp);
}); return result;
} // Adds a new city to the
// in memory store
function createCity(name, description){
cities[name] = description;
return name;
} // Uppercase the city name.
function parseCityName(name){
var parsedName = name[0].toUpperCase() + name.slice(1).toLowerCase();
return parsedName;
} module.exports = router;

[Express] Level 5: Route file的更多相关文章

  1. [Express] Level 5: Route Instance -- refactor the code

    Route Instance Let's rewrite our cities routes using a Route Instance. Create a new Route Instance f ...

  2. [Express] Level 2: Middleware -- 1

    Mounting Middleware Given an application instance is set to the app variable, which of the following ...

  3. [Express] Level 4: Body-parser -- Delete

    Response Body What would the response body be set to on a DELETE request to /cities/DoesNotExist ? H ...

  4. [Express] Level 4: Body-parser -- Post

    Parser Setup Assume the body-parser middleware is installed. Now, let's use it in our Express applic ...

  5. [Express] Level 3: Massaging User Data

    Flexible Routes Our current route only works when the city name argument matches exactly the propert ...

  6. [Express] Level 3: Reading from the URL

    City Search We want to create an endpoint that we can use to filter cities. Follow the tasks below t ...

  7. [Express] Level 2: Middleware -- 2

    Logging Middleware Help finish the following middleware code in the logger.js file: On the response  ...

  8. [Express] Level 1: First Step

    Installing Express Let's start building our new Express application by installing Express. Type the ...

  9. Express web框架 upload file

    哈哈,敢开源,还是要有两把刷子的啊 今天,看看node.js 的web框架 Express的实际应用 //demo1 upload file <html><head><t ...

随机推荐

  1. javascript --- jQuery --- Deferred对象

    javascript --- jQuery --- Deferred对象 javascript的函数式编程是多么引人入胜,jQuery使代码尽可能的精简,intelligent! defer - 必应 ...

  2. win8 VS控件信息

    <TextBlock x:Name="button_1" HorizontalAlignment="Center"  TextWrapping=" ...

  3. Linux中的.emacs文件

    刚开始的时候在Windows下使用emacs,那个时候配置 .emacs文件直接去C盘里\Users\(username)\AppData\Roaming 路径下查找就可以了(最开始的时候可以打开em ...

  4. arp spoofing

    Today our tutorial will talk about Kali Linux Man in the Middle Attack. How to perform man in the mi ...

  5. BFS寻路算法的实现

    关于BFS的相关知识由于水平有限就不多说了,感兴趣的可以自己去wiki或者其他地方查阅资料. 这里大概说一下BFS寻路的思路,或者个人对BFS的理解: 大家知道Astar的一个显著特点是带有启发函数, ...

  6. php 开发最好的ide: PhpStorm

    PhpStorm 跨平台. 对PHP支持refactor功能. 自动生成phpdoc的注释,非常方便进行大型编程. 内置支持Zencode. 生成类的继承关系图,如果有一个类,多次继承之后,可以通过这 ...

  7. HDU 2034 人见人爱A-B 分类: ACM 2015-06-23 23:42 9人阅读 评论(0) 收藏

    人见人爱A-B Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Su ...

  8. HD2046骨牌铺方格

    骨牌铺方格 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submiss ...

  9. 咏南WEB开发框架

    和咏南CS开发框架共享同一个咏南中间件.

  10. python 遍历删除日志

    #! /usr/bin/python2.6#-*- encoding:UTF-8 -*- import osimport os.pathimport time root_dir = os.getcwd ...