[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 ...
随机推荐
- bzoj1833 digit
这道题其实挺水,只是写的时候需要想清楚.我的方法是: 1.将[a,b]转化为[0,b+1)-[0,a) 2.预处理出非0的v在区间[0,10^p)出现次数以及0在区间[0,10^p)出现数 3.将一个 ...
- 三年程序学习之二:(对web初认识)
接着上一篇讲,之后第二天我就来公司上班了,主要是前端,CSS+DIV,table,网站维护之类的,这样的日子过了将近3个星期,一直没什么进展,自己也学不到什么技术,不过我觉得CSS+DIV我算是基础的 ...
- DOM笔记(十):JavaScript正则表达式
一.RegExp ECMAScript通过RegExp类型类支持正则表达式,语法和Perl类似: var exp = /pattern/flags; patternb部分是任何简单的或复杂的正则表达式 ...
- 闲置小U盘变身最强大路由器
小容量 U 盘,用起来嫌容量太少,丢了好像又觉得太可惜.不过现在将它进行一番小改造后,配合我们的电脑 ,就能得到一台强大的路由器,不仅省了买路由的钱,而且这台路由器在市面上基本买不到 ! DD ...
- kali 安装完成后,无法进入界面
vmware 下安装 kali-1.9 ,安装完成后,无法进入界面,提示: 系统出错且无法恢复,请联系管理员 解决办法如下: 在新建虚拟机的时候,选择客户端系统:linux Debian 7. 因 ...
- Use weakref module in a cache or mapping
The weakref module allows the Python programmer to create weak references to objects. In the followi ...
- 【boost】使用lambda表达式和generate_n生成顺序序列
程序中经常用到顺序序列(0,1,2,3,4,5,6.....),一直羡慕python有range这样的函数,而C++中通常只有用循环来处理这种初始化. 现在,结合boost库lambda(虽然差C++ ...
- dom 按着shift多选
<!doctype html> <html> <head> <meta charset="utf-8"> <title> ...
- HD2058The sum problem
The sum problem Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Tot ...
- C++11用于计算函数对象返回类型的统一方法
[C++11用于计算函数对象返回类型的统一方法] 模板 std::result_of 被TR1 引进且被 C++11 所采纳,可允许我们决定和使用一个仿函数其回返值的类别.底下,CalculusVer ...