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 --- 面向对象 --- 封装

    javascript中有原型对象和实例对象 如有疑问请参考:http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_enca ...

  2. python内建函数sorted方法概述

    python中,具体到对list进行排序的方法有俩,一个是list自带的sort方法,这个是直接对list进行操作,只有list才包含的方法:另外一个是内建函数sorted方法,可以对所有可迭代的对象 ...

  3. java开发eclipse常见问题(一)The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

    最近刚开始用Eclipse开发,刚开始都是按教程一步一步的新建web工程也没出现什么问题. 今天选了一个新的workspace,建了个web工程发现最简单的jsp页面都报错:The superclas ...

  4. Java Web高性能开发(二)

    今日要闻: 性价比是个骗局: 对某个产品学上三五天个把月,然后就要花最少的钱买最多最好的东西占最大的便宜. 感谢万能的互联网,他顺利得手,顺便享受了智商上的无上满足以及居高临下的优越感--你们一千块买 ...

  5. java多线程之synchronized(线程同步)

    一.线程同步,主要应用synchronized关键字: public class TraditionalThreadSynchorinzed { public static void main(Str ...

  6. django 搭建自己的博客

    原文链接:http://www.errdev.com/post/4/ 每一个爱折腾的程序员都有自己的博客,好吧,虽然我不太喜欢写博客,但是这样骚包的想法却不断涌现.博客园虽好,可以没有完全的掌控感,搭 ...

  7. 代理模式(proxy)

    1.代理模式 代理模式的作用是:为其他对象提供一种代理以控制对这个对象的访问. 在某些情况下,一个客户不想或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用. 代理模式一般 ...

  8. accordion data-options iconCls

    <div id="aa" class="easyui-accordion" style="width:500px;height:300px;&q ...

  9. webrtc--AudioProcessing的使用

    1.AudioProcessing的实例化和配置: AudioProcessing* apm = AudioProcessing::Create(0); apm->level_estimator ...

  10. 安装glibc2.7

    参考链接http://fhqdddddd.blog.163.com/blog/static/18699154201401722649441/ /lib/libc.so.6: version `glib ...