[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 for the '/cities'
URL path and assign it to thecitiesRoute
variable.
var citiesRoute = app.route('/cities');
Move the code from our previous app.get()
route to a new GET route on the citiesRoute
object.
// GET route for /cities
citiesRoute.get(function (request, response) {
if(request.query.search) {
response.json(citySearch(request.query.search));
} else {
response.json(cities);
}
});
Move app.post()
to citiesRoute
.
// POST route for /cities
citiesRoute.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');
}
});
Now, let's get rid of the citiesRoute
temporary variable and use chaining function calls.
app.route('/cities')
.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');
}
});
Finally, let's move the old routes for the '/cities/:name'
URL path to use the new Route Instance API.
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);
}
});
Before:
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 = {}; var citiesRoute; // GET route for /cities
app.get('/cities', function (request, response) {
if(request.query.search) {
response.json(citySearch(request.query.search));
} else {
response.json(cities);
}
}); // POST route for /cities
app.post('/cities', 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');
}
}); // GET route for /cities/:name
app.get('/cities/:name', function (request, response) {
var cityInfo = cities[request.cityName];
if(cityInfo) {
response.json(cityInfo);
} else {
response.status(404).json('City not found');
}
}); // DELETE route for /cities/:name
app.delete('/cities/:name', 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 result = null;
var search = RegExp(keyword, 'i');
for(var city in cities) {
if(search.test(cities[city])) {
return city;
}
}
} // Adds a new city to the in memory store
function createCity(name, description) {
cities[name] = description;
return name;
} app.listen(3000);
Now:
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 = {}; app.route('/cities')
.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');
}
}); 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);
}
}); // Searches for keyword in description and returns the city
function citySearch(keyword) {
var result = null;
var search = RegExp(keyword, 'i');
for(var city in cities) {
if(search.test(cities[city])) {
return city;
}
}
} // Adds a new city to the in memory store
function createCity(name, description) {
cities[name] = description;
return name;
} app.listen(3000);
[Express] Level 5: Route Instance -- refactor the code的更多相关文章
- [Express] Level 5: Route file
Using a Router Instance Let's refactor app.js to use a Router object. Create a new router object and ...
- [MEAN Stack] First API -- 6. Using Express route instance
For server.js, we update the code by using route instance. By using this, we can remove some duplica ...
- [Express] Level 1: First Step
Installing Express Let's start building our new Express application by installing Express. Type the ...
- [Express] Level 2: Middleware -- 1
Mounting Middleware Given an application instance is set to the app variable, which of the following ...
- [Express] Level 4: Body-parser -- Delete
Response Body What would the response body be set to on a DELETE request to /cities/DoesNotExist ? H ...
- [Express] Level 4: Body-parser -- Post
Parser Setup Assume the body-parser middleware is installed. Now, let's use it in our Express applic ...
- [Express] Level 3: Massaging User Data
Flexible Routes Our current route only works when the city name argument matches exactly the propert ...
- [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 ...
- [Express] Level 2: Middleware -- 2
Logging Middleware Help finish the following middleware code in the logger.js file: On the response ...
随机推荐
- Python的pep8(代码规范)
Python的pep8-代码规范 1. 代码布局设计 1.1 缩进 A. 使用四个空格来进行缩进 B. 换行的时候可以使用反斜杠,最好的方法是使用园括号,在使用反斜杠的时候,在反斜 ...
- ps做gif 登陆下拉菜单效果
作者这里仅介绍登录动画的制作思路和简单过程.一些细节的制作,如登录框,每一帧的图像等都需要自己根据参考图慢慢完成.最终效果 1.新建大小适当的文件,背景填充暗蓝色.首先设计一个底座,主要用图层样式来完 ...
- (转)QR二维码生成及原理
二维码又称QR Code,QR全称Quick Response,是一个近几年来移动设备上超流行的一种编码方式,它比传统的Bar Code条形码能存更多的信息,也能表示更多的数据类型:比如:字符,数字, ...
- 实现带有getMin的栈
题目 实现一个特殊的栈,在实现栈的基础上,再实现返回栈中最小的元素的操作. 要求 pop.push.getMin的时间复杂度是O(1) 可以使用现成的栈类型 思路 如下图所示,在栈结构中,每次pop的 ...
- dom select选单
<!doctype html> <html> <head> <meta charset="utf-8"> <title> ...
- accordion data-options iconCls
<div id="aa" class="easyui-accordion" style="width:500px;height:300px;&q ...
- 如何申请TexturePacker注册码
TexturePacker是一款很强大的游戏图片制作工具,网上有很多关于它的教程和说明,这里不再说它的作用和好处.这里只是说一下如何申请免费的注册码. 国人都习惯了使用免费或者破解的软件,但是使用破解 ...
- 成功获取并更改中兴F660光猫的超级用户密码解除四台限制
上次雷雨后更换的中兴的F660光猫还是很不错的,很稳定,不过超级密码确实记不住,找了些资料,今天成功的更改了密码,简要的写出过程以备下次参考: 第一步:获取超级密码(已知用户名telecomadmin ...
- McAfee VirusScan Enterprise
企业版下载入口: http://www.mcafee.com/cn/downloads/downloads.aspxGrant number:6240017-NAI6240018-NAI 下载Vir ...
- CSS画出的各种形状图
利用CSS可以画出各种需要的图形目录[1]矩形[2]圆形[3]椭圆[4]直角三角形[5]正三角形[6]平行四边形[7]梯形[8]六角星[9]六边形[10]五角星简单图形 矩形div{ width: 1 ...